ios – NSNotificationCenter观察者未收到通知

我知道为什么不收到通知的标准原因:

>取消分配或取消已注册的对象.
>以观察者身份移除对象.
>未注册为观察员.
>注册错误通知或发布错误通知.

我很高兴地说,我很确定这些都不会发生.我想最有可能的是,对象在某些时候被无效并重新创建,但它在初始化时注册通知.

这是我注册的地方:

/**
 *  initialises an object with a unique file url
 *
 *  @param  url                         the url to set as the file url
 */
- (id)initWithFileURL:(NSURL *)url
{
    if (self = [super initWithFileURL:url])
    {
        self.entries                    = [[NSMutableArray alloc] init];

        //  we want to be notified when a note has changed
        [[NSNotificationCenter defaultCenter] addobserver:self
                                                 selector:@selector(noteChanged)
                                                     name:@"com.andbeyond.jamesvalaitis.notesChanged"
                                                   object:self];

        NSLog(@"Just registered for 'com.andbeyond.jamesvalaitis.notesChanged'");
    }

    return self;
}

这是我发布通知的地方:

/**
 *  save the note content
 */
- (void)saveNote
{
    if (_isChanged)
    {
        //  save to the text view to the note's contents
        self.note.noteContent           = self.noteView.text;

        //  post a notification that we changed the notes
        [[NSNotificationCenter defaultCenter] postNotificationName:@"com.andbeyond.jamesvalaitis.notesChanged" object:nil];

        NSLog(@"Just posted 'com.andbeyond.jamesvalaitis.notesChanged'");

        //  make sure we kNow it's already saved
        _isChanged                          = NO;
    }
}

这是未被调用方法

/**
 *  called when a note has changed
 */
- (void)noteChanged:(NSNotification *)notification
{
    NSLog(@"Just received for 'com.andbeyond.jamesvalaitis.notesChanged'");

    //  save the notes
    [self savetoURL:self.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:^(BOOL success)
    {
        if (success)
            NSLog(@"Note updated.");
    }];
}

这是控制台澄清我注册并发布通知

2012-11-15 13:27:50.958 iCloud Custom[11269:907] Just registered for
‘com.andbeyond.jamesvalaitis.notesChanged’

2012-11-15 13:28:24.184 iCloud Custom[11269:907] Just posted
‘com.andbeyond.jamesvalaitis.notesChanged’

The whole project can be found here.

解决方法

我想我已经找到了答案.您正在名为Notesdocument.m的UIDocument文件中创建通知.因此,在创建观察者时,将对象设置为self.这意味着Notesdocument对象.但是当您发布通知时,您将发送对象为零.所以它不会根据文档观察通知.解决这个问题的简单方法是在创建通知时需要将对象设置为nil.否则,您需要传递Notesdocument对象.

查看addobserver通知方法的以下图像和参数详细信息.

检查notificationSender参数.观察者想要接收通知的对象;也就是说,只有此发件人发送的通知才会传递给观察者.

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...