Ios 通过addObserver:selector:name:object调用的多个块操作:
我有一个应用程序,其中用户操作尝试连接到在线资源。连接过程由第三方SDK完成,成功或失败以异步方式发回信号。这由appDelegate处理,我将其配置为以任何方式发布通知。(即Dropbox样式) 下面,假设失败,UIAlertView的调用次数与执行操作的次数相同。也就是说,如果我重复测试连接,但连接失败,第一次调用块一次,第二次调用块两次,第三次调用3次,等等。这就好像没有取消或从队列中删除块操作一样Ios 通过addObserver:selector:name:object调用的多个块操作:,ios,nsoperationqueue,nsnotificationcenter,Ios,Nsoperationqueue,Nsnotificationcenter,我有一个应用程序,其中用户操作尝试连接到在线资源。连接过程由第三方SDK完成,成功或失败以异步方式发回信号。这由appDelegate处理,我将其配置为以任何方式发布通知。(即Dropbox样式) 下面,假设失败,UIAlertView的调用次数与执行操作的次数相同。也就是说,如果我重复测试连接,但连接失败,第一次调用块一次,第二次调用块两次,第三次调用3次,等等。这就好像没有取消或从队列中删除块操作一样 if (!opQ) { opQ = [[NSOperationQueue allo
if (!opQ) {
opQ = [[NSOperationQueue alloc] init];
}
[[NSNotificationCenter defaultCenter] addObserverForName:LINK_NOTIFICATION_FAILURE object:nil queue:opQ usingBlock:^(NSNotification *aNotification) {
dispatch_async(dispatch_get_main_queue(),
^{
[[[UIAlertView alloc] initWithTitle:@"Network_Account_Not_Linked" message:@"Your_attempt_to_link_your_account_ended_unsuccessfully"
delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
[[NSNotificationCenter defaultCenter] removeObserver:self];
});
}];
问题似乎出在addObserverForName:object:queue:usingBlock:上。我使用addObserver:selector:name:object:进行了测试,它工作正常(每个通知执行一个选择器)。使用块更方便,使代码更可读,并允许访问局部变量,这就是我的动机
我在NSBlockOperation线程中尝试了[opQ cancelAllOperations],调度异步(根据调试器,opQ此时处于“范围外”)。此外,使用了具有类似失败结果的[NSOperationQueue mainQueue]。此外,我还尝试在注册通知之前从新的opQ开始。。。娜达
为什么会发生多次呼叫?有没有更好的使用块的方法?针对您正在使用的方法的苹果文档说: 若要取消注册观测,请将此方法返回的对象传递给removeObserver:。在释放addObserverForName:object:queue:usingBlock:指定的任何对象之前,必须调用removeObserver:或removeObserver:name:object: 换句话说,在删除观察者时,您不能简单地传递
self
尝试:
谢谢我试过了,但没有成功。在id observer=。。。第二次发言。我简化了代码,消除了opQ,并使用了[NSOperationQueue mainQueue]。同样的碰撞。消除GCD。。。同样的崩溃。好的,再深入一点,就会发现这个问题是8477629的翻版。答案是添加
\uuu block id observer=…
我打算建议在您的评论之前使用\uu block id…
,哈…我会更新答案。。。
__block id observer = [[NSNotificationCenter defaultCenter] addObserverForName:LINK_NOTIFICATION_FAILURE object:nil queue:opQ usingBlock:^(NSNotification *aNotification) {
dispatch_async(dispatch_get_main_queue(),
^{
[[[UIAlertView alloc] initWithTitle:@"Network_Account_Not_Linked" message:@"Your_attempt_to_link_your_account_ended_unsuccessfully"
delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
[[NSNotificationCenter defaultCenter] removeObserver:observer];
});
}];