对象:在以后的函数中调用块^ {}时访问错误? [英] ObjC: BAD ACCESS when call blocks ^{} in later functions?

查看:105
本文介绍了对象:在以后的函数中调用块^ {}时访问错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遵循此讨论,我遇到了访问错误的问题;

Following this discussion, I've encountered a bad access issue;

一个循环有几个步骤:a,b,c,... x,y,z:

A loop has several steps: a, b, c, ... x, y, z:

-(void)cycle:(float)delta{
[self stepA]
[self stepB]
// etc.
[self stepZ]
}

在某个时候,步骤x会执行以下操作:

At some point, step x does the following:

// IRQ is an NSMutableArray
// Self is a reference to the engine running the cycles
[IRQ addObject:^{ NSLog(@"hello! %@", self); } ];

稍后,步骤z将处理所有延迟的"呼叫:

Later, step z is to process all "delayed" calls:

            for (int i = 0; i < [IRQ count]; i++){
                void (^delayedCall)(void) = [IRQ objectAtIndex:i];
                delayedCall();
            }

            [IRQ removeAllObjects];

结果:EXEC_BAD_ACCESS

Result: EXEC_BAD_ACCESS

现在,如果步骤x仅添加没有对象引用的纯字符串,如下所示,则步骤Z可以正常工作:

Now, if step x only adds a plain string with no object reference like follows, step Z works fine:

[IRQ addObject:^{ NSLog(@"hello!"); } ];

最后观察,如果同一步骤既将块添加到队列中又遍历队列以执行块,则不会发生任何问题. 就像对对象的引用在步骤中丢失"一样:方法还剩下吗?

Last observation, if a same step both adds blocks to the queue AND iterates over the queue to execute the blocks, then no problem occurs. Like the reference to an object gets "lost" as the step: method is left?

我在这方面不太了解,将需要更多帮助!

I don't understand much in this area and will need more help!

詹姆斯,只是尝试了以下方法来避免这种参考循环:

edit: James, just tried the following to avoid that reference cyle:

NSString *userName = @"James";
[IRQ addObject:^{ NSLog(@"hello %@", userName); } ];

,它也会发生.您的解决方案将如何应用于此?

and it also happens. How would your solution apply to this?

提前谢谢!

推荐答案

使用^{}语法创建块时,将在堆栈上创建该块.要长时间保留该块(超出创建它的函数的范围),必须将块复制到堆中:

When you create a block with the ^{} syntax, it's created on the stack. To persist the block for a long period of time (beyond the scope of the function that creates it), you must copy the block into the heap:

void (^ myBlock)(void) = ^ {
    // your block code is here.
};
[IRQ addObject:[[myBlock copy] autorelease]];

如果使用ARC,请跳过-autorelease消息.

If using ARC, skip the -autorelease message.

这篇关于对象:在以后的函数中调用块^ {}时访问错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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