如果它是一个异步调用,这将是有意义的创建实际块内的NSMutableArray
:
[self performOperationWithBlock:^(void)
{
NSMutableArray *objArray = [[NSMutableArray alloc] initWithCapacity:0];
//adding objects to objArray
.
.
//operation with objArray finished
// 1. should objArray be released here?
}];
正如你不会需要它的后块(它只对异步操作的持续时间有意义),所以最终在你使用它之后释放它。或者,你可以简单地:
NSMutableArray *objArray = [NSMutableArray array];
而在这种情况下,你不需要释放它。
如果是同步呼叫,则应该在release
之后。
注:我假设你的块,这意味着它是有道理的块开始之前要创建上使用之前填充NSMutableArray
。
异步方法:
-(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
}
同步方法:
它假设你需要立即的结果,这是有道理的,当你做进一步的工作与阵列,后挡已执行,因此:
-(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];
}
'__block'表示您不希望块保留一个rray,所以版本2更合乎逻辑。我会在施工时使用'autorelease'。 –
如果您只是想将对象添加到块中的数组中,则不需要'__block'。 –