Graphics Programs Reference
In-Depth Information
- (BNRItem *)someItem
{
BNRItem *item = [[[BNRItem alloc] init] autorelease];
return item;
}
Because you had to send the
release
message to an object to relinquish ownership, the
caller of this method had to understand its its ownership responsibilities. But it was easy
to get confused.
BNRItem *item = [BNRItem someItem]; // I guess I own this now?
NSString *string = [item itemName]; // Well if I own that, do I own this?
Thus, objects created by methods other than
alloc
and
copy
would be sent
autore-
lease
before being returned, and the receiver of the object would take ownership as
needed or just let it be destroyed after using it within the method in which it was returned.
With ARC, this is done automatically (and sometimes optimized out completely). An
autorelease pool is created by the
@autoreleasepool
directive followed by curly
brackets. Inside those curly brackets, any newly instantiated object returned from a meth-
od that doesn't have
alloc
or
copy
in its name is placed in that autorelease pool. When
the curly bracket closes, any object in the pool loses an owner.
@autoreleasepool {
// Get a BNRItem back from a method that created it, method doesn't say alloc/copy
BNRItem *item = [BNRItem someItem];
} // item loses an owner and is destroyed because nothing else took ownership of it
iOS applications automatically create an autorelease pool for you, and you really don't
have to concern yourself with it. But isn't it nice to know what that
@autore-
leasepool
is for?