【发布时间】:2014-06-20 18:43:03
【问题描述】:
我在 AppDelegate 中有以下代码。目的是创建几个观察者,然后调用一些代码。一旦该代码完成它就会发布一个通知,然后观察者应该删除两个观察者并调用完成处理程序。
我的问题是观察者似乎没有像我预期的那样被移除。通知已发布,NSLog 条目已写入控制台,因此我知道观察者正在工作。但是,在第二次调用时,NSLog 被调用了两次,第三次调用了 3 次等等。
我的想法是,这与从观察者运行的代码块中的删除有关,但是,我不确定如何解决这个问题(如果确实是这个问题的话)。
有人能解释一下我是如何做到这一点的吗?
谢谢。
-(void) application:(UIApplication *)application performFetchWithCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
[[NSNotificationCenter defaultCenter] addObserverForName:@"fetchDidCompleteNewData" object:nil
queue:nil usingBlock:^(NSNotification *completed) {
//Remove Observers
[[NSNotificationCenter defaultCenter] removeObserver:self
name:@"fetchDidCompleteNewData"
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:@"fetchDidCompleteNoData"
object:nil];
// Post completion
completionHandler(UIBackgroundFetchResultNewData);
NSLog(@"Background fetch completed... New Data");
}];
[[NSNotificationCenter defaultCenter] addObserverForName:@"fetchDidCompleteNoData" object:nil
queue:nil usingBlock:^(NSNotification *completed) {
//Remove Observers
[[NSNotificationCenter defaultCenter] removeObserver:self
name:@"fetchDidCompleteNoData"
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:@"fetchDidCompleteNewData"
object:nil];
//post completion
completionHandler(UIBackgroundFetchResultNoData);
NSLog(@"Background fetch completed... No New Data");
}];
GetDetails *getDetails = [[GetDetails alloc] init];
[getDetails backgroundRefresh];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
return YES;
}
【问题讨论】:
标签: ios objective-c nsnotificationcenter observers