我在代码中使用NSNotificationCenter。
[[NSNotificationCenter defaultCenter]addObserverForName:@"NextIndexNotification" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
[self receiveTestNotification:note];
[[NSNotificationCenter defaultCenter] removeObserver:note];
}];
- (void)receiveTestNotification:(NSNotification *) notification
{
NSDictionary *userInfo = notification.userInfo;
NSString *strServerResultID = [userInfo objectForKey:@"valServerResultID"];
}
////我在这里添加通知中心......
dispatch_async(dispatch_get_main_queue(),^{
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%@",[[PerformXMLXPathQuery(responseData,xPathQuery) objectAtIndex:0] valueForKey:kNodeContent]] forKey:@"valServerResultID"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"NextIndexNotification" object:self userInfo:userInfo];
});
在此代码中,删除通知未被调用,我的代码移动到无限循环。
我在哪里做错了?
答案 0 :(得分:0)
不是传递note
(通知本身而不是观察者),而是将addObserverForName
调用的返回值传递给removeObserver
,如下所示:
__block id observer = [[NSNotificationCenter defaultCenter] addObserverForName:@"NextIndexNotification"
object:nil
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note)
{
[self receiveTestNotification:note];
[[NSNotificationCenter defaultCenter] removeObserver:observer];
}];
答案 1 :(得分:0)
试试 [[NSNotificationCenter defaultCenter] removeObserver:nil];
答案 2 :(得分:0)
使用blocks删除通知。
[[NSNotificationCenter defaultCenter] removeObserver:self];