Jerry Ray Jerry Ray - 6 months ago 25
Objective-C Question

How can I manage memory in a loop under ARC without @autoreleasepool block

As before, we usually do something for loop like this:

for (int i = 0 ; i < 5; i ++) {
NSNumber * number = [[NSNumber alloc] initWithInt:i];
[muArray addObject:number];
[number release];
}


But under ARC, there is no
release
. Can I manage memory without an
@autorelease
block, like this (directly remove release statement):

for (int i = 0 ; i < 5; i ++) {
NSNumber * number = [[NSNumber alloc] initWithInt:i];
[muArray addObject:number];
}





Similarly, is the
@autoreleasepool
necessary, like this?

for (int i = 0 ; i < 5; i ++) {
@autoreleasepool{
NSNumber * number = [NSNumber numberWithInt:i];
[muArray addObject:number];
}
}

Answer

Your second code block (compiled with ARC), has exactly the same semantics as your first code block (compiled with MRC).

Under ARC, when you set a strong object reference to nil, or when a strong object reference is destroyed, ARC takes care of sending the release message for you. In both examples, the number variable is destroyed at the end of the loop body, so (in the second example) ARC releases the objected that number referenced.

In your third example, the @autoreleasepool will cause the returned NSNumber to be released on each pass through the loop. This might be necessary for a large number of loop iterations. For just five iterations, each creating a single NSNumber, it's not necessary.