ios取消注册观察者

时间:2013-05-17 14:24:00

标签: ios objective-c

我正在阅读Apple Documents并看到:

  

在观察通知的对象被解除分配之前,它   必须告知通知中心停止发送通知。   否则,下一个通知将被发送到不存在的对象   程序崩溃。

我试图让应用程序崩溃以更好地了解它是如何工作的。

但是,即使我没有将此代码放在SecondViewController dealloc中,它仍然不会在发送通知后崩溃。我显然是添加观察者并从secondViewController返回并在viewController中推送通知。那么,如果这个程序没有崩溃,为什么我们需要删除观察者?

  

[[NSNotificationCenter defaultCenter] removeObserver:self];

Rest代码是:

//的ViewController:

@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]; }

// SecondViewController:

@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:^{}]; }

2 个答案:

答案 0 :(得分:2)

@Reno Jones是对的。 像这样删除观察者 - [[NSNotificationCenter defaultCenter] removeObserver:self name:@"TestNotification" object:nil];

要回答的另一件事是你应该删除- (void)dealloc {}方法中的观察者 - 这是在释放self时调用的方法。

编辑:

我查看了代码,我发现你没有使用arc。还有一个问题,为什么你不在你的应用程序中使用ARC?你有充分的理由用引用计数来强调自己,我不明白这一点吗?

其次,您可以在viewDidLoad方法中移动addObserver,看看它是否会导致您的应用崩溃。

答案 1 :(得分:0)

由于对象仍在内存中,因此dealloc的{​​{1}}方法未被调用,或者在取消分配控制器后未调用SecondViewController方法。否则,肯定会崩溃。确保通过放置断点来调用方法。