Reputation: 21966
I have understood how @autoreleasepool works, I have the newest version of xcode where ARC is supported.So I can use it, but I failt to understand how it works inside a class.
Let's suppose that I have this interface:
@interface AppDelegate : NSObject <NSApplicationDelegate>
{
@private
NSMutableDictionary* dictionary;
}
And that I allocate and initialize the dictionary in init method:
- (id) init
{
self= [super init];
if(self)
{
dictionary=[[NSMutableDictionary alloc]init];
}
return self;
}
In the dealloc method I can't send to dictionary the release message, because I am under ARC.So when I usually allocate memory I do something like that:
@autoreleasepool
{
NSMutableDictionary* dict=[[NSMutableDictionary alloc]init];
< use it>
}
PS: Pardon syntax errors, I have written it directly without compiling.
But in the class, where do I put the "@autoreleasepool" block?
Upvotes: 1
Views: 814
Reputation: 10772
You can place an @autoreleasepool
block around any section of code, however you really shouldn't do what I think you're doing.
Autorelease is much less efficient than allowing ARC to add in retain and release calls for you, and it's potentially unsafe. Autorelease puts all of your objects in a "pool" and then when you're out of scope and/or whenever it decides to dump the pool, it "drains" the pool and the objects' retain counts get decremented by one.
The short answer: Leave out the @autorelease
blocks completely unless Apple says otherwise in the documentation or the template (for example, main.m will have an @autoreleasepool
in it).
This means that your objects could potentially get released before you really wanted them to. @autoreleasepool
blocks are more useful for when you have a very tight loop of code that's going to instantiate and then discard a massive amount of objects. For example, a for loop that processes a huge database and allocates string objects and then uses those string objects to fill the properties of instances of a class you've created. In this case, ARC may not release those objects reliably while you're inside the for loop and you may need to create an autorelease pool.
However, ARC not doing the right thing in a tight loop isn't very common. It's really more of a non-ARC concept, where you use an NSAutoreleasePool
and you manually drain it.
Upvotes: 3