正确管理addObserverForName:object:queue:usingBlock: [英] Correct management of addObserverForName:object:queue:usingBlock:

查看:591
本文介绍了正确管理addObserverForName:object:queue:usingBlock:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍然是新的,在objective-c块,想知道我有这个伪装的代码是否正确。我不知道是否足以删除观察者,或者如果我必须调用removeObserver:name:object:

I'm still new to blocks in objective-c and wondering if I have this psuedo code correct. I'm not sure if it's enough to just remove the observer or if i have to call removeObserver:name:object:

-(void) scan {
    Scanner *scanner = [[Scanner alloc] init];
    id scanComplete = [[NSNotificationCenter defaultCenter] addObserverForName:@"ScanComplete" 
                        object:scanner 
                        queue:nil 
                        usingBlock:^(NSNotification *notification){
                            /*
                             do something
                             */
                            [[NSNotificationCenter defaultCenter] removeObserver:scanComplete];
                            [scanner release];
                        }];
    [scanner startScan];
}



更新:我正在接收间歇性 EXC_BAD_ACCESS <

Update: I'm receiving intermittent EXC_BAD_ACCESS from this block, so this can't be right.

推荐答案

声明 scanComplete 变量,然后定义块本身。

Declare the scanComplete variable before defining the block itself.

你需要这样做的原因是因为你试图访问一个变量

The reason why you need to do this is because you're trying to access a variable that doesn't exist within the block at the time of definition since the variable itself has not been assigned yet.

什么是 EXC_BAD_ACCESS ?嗯,当你尝试访问不存在的引用时,它是一个异常。

What is EXC_BAD_ACCESS? Well, it's an exception that is thrown when you try to access a reference that doesn't exist. So that is exactly the case in your example.

所以如果你在块本身之前声明变量,那么它应该工作:

So if you declare the variable before the block itself, then it should work:

-(void) scan {
    Scanner *scanner = [[Scanner alloc] init];
    __block id scanComplete;
    scanComplete = [[NSNotificationCenter defaultCenter] addObserverForName:@"ScanComplete" 
                        object:scanner 
                        queue:nil 
                        usingBlock:^(NSNotification *notification){
                           /*
                           do something
                           */
                           [[NSNotificationCenter defaultCenter] removeObserver:scanComplete];
                           [scanner release];
                    }];
    [scanner startScan];
}

这篇关于正确管理addObserverForName:object:queue:usingBlock:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆