Search code examples
iphonereleasensautoreleasepoolalloc

iPhone Autoreleasepool and allocations


I've been reading about autoreleasepool but there is a point which is a bit unclear to me. I have some functionality using threads that required seperate memory managment using autoreleasepool.

In the following example is correct

-(void) doSomething {

   NSAutorelease *pool = [[NSAutorelasepool alloc] init];

   NSString *myString = @"Hello";

   [pool release];
}

Is this correct?

-(void) doSomething {

   NSAutorelease *pool = [[NSAutorelasepool alloc] init];

   NSString *myString = [[NSString alloc] initWithString:@"Hello"];

   [pool release];
}

or this?

-(void) doSomething {

   NSAutorelease *pool = [[NSAutorelasepool alloc] init];

   NSString *myString = [[NSString alloc] initWithString:@"Hello"];

   [myString release];
   [pool release];
}

My question is owned objects created in the scope of the autorelease pool need to be relased specifically or are the taken care of when the autorelasepool is been released?

Teo


Solution

  • Autorelease pool handles the autoreleased objects. If you own an object (via alloc or copy or retain) then you must release it. So your 2nd example is not correct. As you have allocated the string, you own it and you must release it.

    An autorelease pool is created for the main thread. (You can look into the main function if you want). Every thread need its own autorelease pool to manage autoreleased objects. That's why if you create another thread then you must create an autorelease pool for that thread. Even if you don't create autoreleased object in the thread, you should create this as the library calls in that thread may create autoreleased objects. Even if you are sure that no library calls are making autoreleased objects then you also should create them as that is the best practice, specially if you are working on big project which is developed and maintained by multiple people.