我正在阅读 Apple 文档并看到:
Before an object that is observing notifications is deallocated, it must tell the notification center to stop sending it notifications. Otherwise, the next notification gets sent to a nonexistent object and the program crashes.
我尝试让应用程序崩溃,以更好地了解它的实际工作原理。
但是,即使我没有将此代码放入 SecondViewController dealloc 中,发送通知后它仍然不会崩溃。显然我正在添加观察者并从 SecondViewController 返回并在 viewController 中推送通知。那么,如果这个程序不会崩溃,为什么我们需要删除观察者呢?
[[NSNotificationCenter defaultCenter] removeObserver:self];
其余代码是:
// View Controller :
@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]; }
//第二个 View Controller :
@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:^{}]; }
最佳答案
@Reno Jones 是对的。
像这样删除观察者 - [[NSNotificationCenter defaultCenter] removeObserver:self name:@"TestNotification"object:nil];
在他的答案中还要添加的一件事是,您应该删除 - (void)dealloc {}
方法中的观察者 - 这是释放 self 时调用的方法。
编辑:
我查看了代码,发现您没有使用 arc。还有一个问题,为什么你不在你的应用程序中使用 ARC?你有充分的理由通过引用计数来给自己施加压力吗?我不明白这一点?
其次,您可以在 viewDidLoad 方法中移动 addObserver 并查看它是否会导致您的应用程序崩溃。
关于ios 取消注册观察者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16611450/