我正在阅读 Apple Documents 并看到:
在一个观察通知的对象被释放之前,它必须告诉通知中心停止向它发送通知。否则,下一个通知将被发送到一个不存在的对象并且程序崩溃。
我试图让应用程序崩溃以更好地了解它是如何工作的。
但是,即使我没有将这段代码放入 SecondViewController 的 dealloc 中,它在发送通知后仍然不会崩溃。我显然正在添加观察者并从 secondViewController 返回并在 viewController 中推送通知。那么,如果这个程序没有崩溃,为什么我们需要移除观察者呢?
[[NSNotificationCenter defaultCenter] removeObserver:self];
休息代码是:
//视图控制器:
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. }
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated. }
- (IBAction)go:(id)sender {
SecondViewController *secondViewController = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
[self presentViewController:secondViewController animated:NO completion:^{}];
[secondViewController release], secondViewController = nil; }
- (IBAction)push:(id)sender {
// All instances of TestClass will be notified
[[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" object:self]; }
//第二视图控制器:
@implementation SecondViewController
- (void)dealloc {
[super dealloc]; }
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(receiveTestNotification:)
name:@"TestNotification"
object:nil];
}
return self; }
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void) receiveTestNotification:(NSNotification *) notification {
// [notification name] should always be @"TestNotification"
// unless you use this method for observation of other notifications
// as well.
NSLog (@"Successfully received the test notification!"); }
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated. }
- (IBAction)back:(id)sender {
NSLog(@"");
[self dismissViewControllerAnimated:NO completion:^{}]; }