ARC:从块内部,委托方法内部调用方法时,EXC_BAD_ACCESS [英] ARC: EXC_BAD_ACCESS when calling a method from inside a block, inside a delegate method

查看:92
本文介绍了ARC:从块内部,委托方法内部调用方法时,EXC_BAD_ACCESS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在委托方法内部创建了一个块,并使用它在另一个类中调用静态方法.即使启用了NSZombies,我也会收到EXC_BAD_ACCESS错误.关于类似问题,这里有几篇文章-我认为这是最接近的文章:

I created a block, inside a delegate method and I am using it to call a static method in another class. I am getting an EXC_BAD_ACCESS error even when I have NSZombies enabled. There are a few posts on here about similar problems - I think this one is the closest:

ARC:从中获取EXC_BAD_ACCESS委托方法中使用的内部块

但是,到目前为止,我还没有发现有任何帮助.这是代码:

But, I haven't found anything so far that has helped. Here is the code:

@interface MyClass()
@property (nonatomic, copy) CaseBlock c;
@end

....

//NSURLConnection delegate method
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{        
    NSDictionary *d = [NSDictionary dictionaryWithObjectsAndKeys:
                       //blows up after executing this
                       ^() { [AnotherClass staticMethod]; },authURL,
                       ^() { NSLog(@"TODO");}, searchURL,
                       ^() { NSLog(@"TODO"); }, itemURL,
                       nil];
    self.c = [[d objectForKey:[self.url path]] copy];

    if (self.c) {
        self.c();
    } else { NSLog(@"WARN unexpected response path"); }

}

这是我第一次尝试使用块,但是我可以说这是引起问题的原因,因为从块外部调用方法效果很好.而且,据我所知,我编写的所有代码实际上都已执行,然后发生EXC_BAD_ACCESS错误.但是,我是Objective-C的新手,所以如果我错了,请纠正我.

This is the first time that I have tried to use blocks, but I can tell that this is causing the problem because calling the method from outside the block works fine. And also, as far as I can tell, all of the code that I wrote actually gets executed AND THEN the EXC_BAD_ACCESS error happens. But, I am new to Objective-C so, please correct me if I am wrong about that.

推荐答案

如果块需要超出其创建范围,则需要复制块.由于dictionaryWithObjectsAndKeys:处理一般对象而不是专门处理块,因此它不会不知道要复制它们,因此您必须先复制它们,然后再将其传递给它.

You need to copy blocks if they need to outlive the scope they were created in. Since dictionaryWithObjectsAndKeys: deals with objects in general and not specifically blocks, it doesn't know to copy them, so you must copy them before passing them to it.

NSDictionary *d = [NSDictionary dictionaryWithObjectsAndKeys:
                   //blows up after executing this
                   [^() { [AnotherClass staticMethod]; } copy], authURL,
                   [^() { NSLog(@"TODO");} copy], searchURL,
                   [^() { NSLog(@"TODO"); } copy], itemURL,
                   nil];

这篇关于ARC:从块内部,委托方法内部调用方法时,EXC_BAD_ACCESS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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