iOS NSNotificationCenter Observer未被删除
我在AppDelegate中有以下代码。 目的是创建几个观察者,然后调用一些代码。 一旦该代码完成,然后发布通知,然后观察者应该删除两个观察者并调用完成处理程序。
我的问题是看来观察员没有像我预期的那样被删除。 发布通知,并将NSLog条目写入控制台,因此我知道观察者正在工作。 但是,在第二次调用时,NSLog被调用两次,第三次调用三次等。
我的想法是,这与在观察者运行的代码块内的删除有关,但是,我不确定如何解决这个问题(如果这确实是问题所在)。
有人可以如此善良地解释我是如何实现这一目标的吗?
谢谢。
-(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; }
您没有将self
注册为对象。 此外,当块被addObserverForName:
压入堆栈时addObserverForName:
该方法尚未返回,因此notification
为nil
。
使用block
一个全局对象,例如
__block __weak id notification;
然后,
notification = [[NSNotificationCenter defaultCenter] addObserverForName:@"fetchDidCompleteNewData" object:nil queue:nil usingBlock:^(NSNotification *completed) { //Remove Observers [[NSNotificationCenter defaultCenter] removeObserver:notification]; }];
我的想法是,这与在观察者运行的代码块内的删除有关,但是,我不确定如何解决这个问题(如果这确实是问题所在)。
有人可以如此善良地解释我是如何实现这一目标的吗?
当然。
您可以通过不使用addObserverForName:object:queue:usingBlock:
方法而使用addObserver:selector:name:object:
方法轻松测试您的理论,其中selector
是您调用的函数的名称而不是使用块。
只需使用NSNotificationCenter的API指南来获取有关这些方法的详细信息,或者一般情况下,因为您质疑的是您可以使用哪种不需要块语句的方法,所以咨询API是第一个检查其中的替代工具的地方。类。
- 使用自定义UITableViewCells(一条破损的logging)改进了ViewController的加载速度
- dismissViewControllerAnimated在块内不起作用
- iOS开发部分-5
- 可可触摸(WWDC 2017 Session 201)TL; DR中的新增功能
- 如何从appDelegate展示UIAlertView
- 对于仅iPhone,iOS 7+应用程序,我们可以只包含@ 3x图像吗?
- 获取ios 8自定义键盘扩展的“由于内存错误而终止”
- 从iOS服务器上的UDP服务器接收数据不能从Linux服务器上工作,但从MacBook Pro工作
- 无法将“CustomProfileCell”类型的返回表达式转换为返回类型“UITableViewCell”