为什么Objective-C块仍然工作,而不将其复制到堆? [英] Why does Objective-C block still work without copying it to the heap?
问题描述
我在类中有一个简单的方法:
I have a simple method in my class:
- (void)getFormWithBlock:(DataCenterResultBlock)block {
[SomeClass doSomeLongOperationWithParam:someParam
completionBlock:^(NSData *data, NSURLResponse *response) {
//Success
block(aVar, YES);
} errorBlock:^(NSError *error) {
//Failed
block(nil, NO);
}];
}
我读到,如果你异步地做某事,你应该将块复制到堆因为它们在堆栈上分配,一旦调用树回绕,它就会消失。
I read that you should copy blocks to the heap if you are doing something asynchronously because they are allocated on stack and once the call tree rewinds it will be gone.
但是这里,我不是把它复制到堆,但仍然没有崩溃。为什么?
感谢
But here, I am not copying it to heap but still I get no crash. Why? Thanks
推荐答案
7.5。块
7.5. Blocks
...
__通过初始化堆将可保留对象所有者类型的块变量移出堆栈
__block variables of retainable object owner type are moved off the stack by initializing the heap copy with the result of moving from the stack copy.
编辑我认为我误解了这个问题:询问有关块对象自己,而不是阻止变量。在这种情况下的答案略有不同,但它归结为相同的:ARC自动正确的事情。
EDIT I think I misunderstood the question: you asked about block objects themselves, not block variables. The answer in this case is slightly different, but it boils down to the same this: ARC does the correct thing automatically.
ARC知道块字面量必须被复制,如果它们在当前作用域返回后使用。非ARC代码需要显式复制并自动释放返回的块:
ARC knows that block literals must be copied if they're used after the current scope returns. Non-ARC code needs to explicitly copy and autorelease returned blocks:
return [[^{
DoSomethingMagical();
} copy] autorelease];
使用ARC,它变成:
With ARC, this simply becomes:
return ^{ DoSomethingMagical(); };
(来自此处)
这篇关于为什么Objective-C块仍然工作,而不将其复制到堆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!