gpt4 book ai didi

ios - NSNotificationCenter 观察者未收到通知

转载 作者:可可西里 更新时间:2023-11-01 03:06:26 27 4
gpt4 key购买 nike

我知道未收到通知的标准原因:

  • 取消分配或取消已注册的对象。
  • 作为观察者移除对象。
  • 未注册为观察员。
  • 注册错误的通知或发布错误的通知。

我可以很高兴地说,我非常确定这些都没有发生。我想最有可能的是该对象在某个时候被取消并重新创建,但它在初始化时注册了通知。

这是我注册的地方:

/**
* 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.mUIDocument 文件中创建通知。所以当你创建一个观察者时,你将对象设置为self。这意味着 NotesDocument 对象。但是当您发布通知时,您发送的对象是nil。所以 它不会根据文档观察到通知解决此问题的简单方法是在创建通知时将对象设置为 nil。否则,您需要传递一个 NotesDocument 对象

查看下图和参数详细信息,了解 addObserver 通知方法。

enter image description here

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

关于ios - NSNotificationCenter 观察者未收到通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13398633/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com