2

我正在阅读 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:^{}]; }
4

2 回答 2

2

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

要添加到他的答案中的另一件事是您应该删除- (void)dealloc {}方法中的观察者 - 这是释放 self 时调用的方法。

编辑:

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

其次,您能否在 viewDidLoad 方法中移动 addObserver 并查看它是否会使您的应用程序崩溃。

于 2013-05-17T14:32:25.843 回答
0

由于对象仍在内存中,因此没有调用方法,或者dealloc在释放控制器后未调用方法。否则,它肯定会崩溃。确保通过放置断点来调用方法。SecondViewControllerpush:(id)sender

于 2013-05-17T14:47:02.667 回答