调用带变量的块是否保证其生命周期将被保留?

时间:2012-12-16 16:24:33

标签: objective-c automatic-ref-counting objective-c-blocks

我有一些typedef:

typedef void (^myBlock)(SomeObject);

我有一些对象

@interface SomeObject : NSObject
@end

// Method of some arbitrary class
- (void) someMethod1 {
    SomeObject *someObject = [[SomeObject alloc] init];

    myBlock block = ^(SomeObject obj){
        // When _block(someObject)_ will be called inside someQueue - 
        // Is it guaranteed that someObject will be alive, retained inside me?       

        // Do something complex and involving (or not) obj ...    
    }

    dispatch_async(someQueue, ^{
        // Some bunch of code - after which we are sure that 
        // by the next line someMethod1 will run out, so its scope is lost

        block(someObject);
    });
}

问题放在变量的块中:是否保证我们传递给 someQueue 队列内的块的someObject对象将活着并保留块中?

这个问题是我刚问过的问题的一个更复杂的变化:Does a passing of an object to a block guarantee that its lifecycle will be retained?

2 个答案:

答案 0 :(得分:1)

该块以及它将使用的所有内容将一直保留到块执行之后.. 已捕获

答案 1 :(得分:0)

我相信你提出的问题与上一个问题相同。这里唯一的区别是你没有在区块内调用方法,而是在调用一个区块。
也许我的答案还不够明确:一切都保留在一个区块内,即使是一个区块也是如此。

dispatch_async(someQueue, ^{
    // Some bunch of code - after which we are sure that 
    // by the next line someMethod1 will run out, so its scope is lost

    block(someObject);
});

在块内部,您调用someObject,因此捕获someObject。此外,块也被捕获。