ind*_*gie 6 cocoa-touch objective-c nsnotification nsnotificationcenter ipad
在我的iPad应用程序中,在一个类中我注册了一个通知:
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(selectedList:) name:@"TTSelectedList" object:nil];
Run Code Online (Sandbox Code Playgroud)
我的selectedList:方法看起来像这样:
- (void)selectedList:(NSNotification*)notification
{
NSLog(@"received notification");
}
Run Code Online (Sandbox Code Playgroud)
然后在另一个类(a UITableViewController)中,当选择一行时,我发布该通知:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"posting notification");
[[NSNotificationCenter defaultCenter] postNotificationName:@"TTSelectedList" object:nil];
}
Run Code Online (Sandbox Code Playgroud)
我可以确认通知正在发布,因为"发布通知"被记录到控制台,但是从未调用"已接收通知",这意味着未收到通知且未调用选择器.我无法弄清楚造成这种情况的原因.
谢谢
Rob*_*ier 14
最可能的原因是你实际上没有打电话addObserver:selector:name:object:.你那里没有伐木线; 你确定代码正在运行吗?
第二个最可能的原因是您在removeObserver:发布通知之前进行了呼叫.这种情况最为常见dealloc(如果你曾经观察过任何事情,应该随时打电话removeObserver).这里的错误是你的观察对象在通知之前已经解除分配.