我有以下代码片段:
-(void) doSomething
{
__block NSMutableArray *objArray = [[NSMutableArray alloc] initWithCapacity:0];
[self performOperationWithBlock:^(void)
{
//adding objects to objArray
.
.
//operation with objArray finished
// 1. should objArray be released here?
}];
//2. should objArray be released here?
}
我应该自动释放 objArray 吗?
最佳答案
如果是异步调用,在实际 block 中创建 NSMutableArray
是有意义的:
[self performOperationWithBlock:^(void)
{
NSMutableArray *objArray = [[NSMutableArray alloc] initWithCapacity:0];
//adding objects to objArray
.
.
//operation with objArray finished
// 1. should objArray be released here?
}];
因为在 block 之后你不会需要它(它只在异步操作期间有意义),所以最后在你使用它之后释放它。或者,您可以简单地:
NSMutableArray *objArray = [NSMutableArray array];
在这种情况下,您不需要释放它。
如果是同步调用,您应该在 block 之后释放
它。
注意:我假设您在 block 上使用之前填充 NSMutableArray
,这意味着在 block 开始之前创建是有意义的。
异步方法:
-(void) doSomething
{
// Remove the `__block` qualifier, you want the block to `retain` it so it
// can live after the `doSomething` method is destroyed
NSMutableArray *objArray = // created with something useful
[self performOperationWithBlock:^(void)
{
// You do something with the objArray, like adding new stuff to it (you are modyfing it).
// Since you have the __block qualifier (in non-ARC it has a different meaning, than in ARC)
// Finally, you need to be a good citizen and release it.
}];
// By the the time reaches this point, the block might haven been, or not executed (it's an async call).
// With this in mind, you cannot just release the array. So you release it inside the block
// when the work is done
}
同步方法:
它假定您立即需要结果,并且当您进一步使用 Array 时,在执行该 block 之后,它是有意义的,因此:
-(void) doSomething
{
// Keep `__block` keyword, you don't want the block to `retain` as you
// will release it after
__block NSMutableArray *objArray = // created with something useful
[self performOperationWithBlock:^(void)
{
// You do something with the objArray, like adding new stuff to it (you are modyfing it).
}];
// Since it's a sync call, when you reach this point, the block has been executed and you are sure
// that at least you won't be doing anything else inside the block with Array, so it's safe to release it
// Do something else with the array
// Finally release it:
[objArray release];
}
关于ios - 在哪里释放 __block 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21188483/