ARC doesn't get rid of retains, releases and autoreleases, it just adds in the required ones for you. So there are still calls to retain, there are still calls to release, there are still calls to autorelease and there are still auto release pools.
One of the other changes they made with the new Clang 3.0 compiler and ARC is that they replaced NSAutoReleasePool
with the @autoreleasepool
compiler directive. NSAutoReleasePool
was always a bit of a special "object" anyway and they made it so that the syntax of using one is not confused with an object so that it's generally a bit more simple.
So basically, you need @autoreleasepool
because there are still auto release pools to worry about. You just don't need to worry about adding in autorelease
calls.
An example of using an auto release pool:
- (void)useALoadOfNumbers {
for (int j = 0; j < 10000; ++j) {
@autoreleasepool {
for (int i = 0; i < 10000; ++i) {
NSNumber *number = [NSNumber numberWithInt:(i+j)];
NSLog(@"number = %p", number);
}
}
}
}
A hugely contrived example, sure, but if you didn't have the @autoreleasepool
inside the outer for
-loop then you'd be releasing 100000000 objects later on rather than 10000 each time round the outer for
-loop.
Update:
Also see this answer - https://stackoverflow.com/a/7950636/1068248 - for why @autoreleasepool
is nothing to do with ARC.
Update:
I took a look into the internals of what's going on here and wrote it up on my blog. If you take a look there then you will see exactly what ARC is doing and how the new style @autoreleasepool
and how it introduces a scope is used by the compiler to infer information about what retains, releases & autoreleases are required.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…