gpt4 book ai didi

iOS NSNotificationCenter 观察者未被删除

转载 作者:可可西里 更新时间:2023-11-01 17:07:20 25 4
gpt4 key购买 nike

我在 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 注册为对象。此外,当 block 被 addObserverForName: 压入堆栈时,该方法尚未返回,因此 notificationnil

使用block创建一个全局对象,例如

__block __weak id notification;

然后,

notification =  [[NSNotificationCenter defaultCenter] addObserverForName:@"fetchDidCompleteNewData" object:nil queue:nil usingBlock:^(NSNotification *completed) {

//Remove Observers
[[NSNotificationCenter defaultCenter] removeObserver:notification];
}];

关于iOS NSNotificationCenter 观察者未被删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23455956/

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