views:

69

answers:

1

Hi, Im used to c programming where im responsible for freeing everything, and this objective c funky stuff is throwing some spanners in the work. I am using the below code.

NSArray *b = [a allObjects];
NSArray *c = [b sortedArrayUsingDescriptors:sortDescriptors];

Who's responsible for releasing "b" and "c". For the record, "a" is a NSSet. If I release them manually it seems to crash the app, but I'm not 100% sure so I thought Id ask.

Thanks.

+10  A: 

Both of those calls return autoreleased objects, so you're safe. They'll be deallocated for you (sometime in the future, at the end of the current run loop for example).

The general rule is that if you don't explicitly call retain, alloc, or one of the object's copy methods, you get an autoreleased object back from whatever method you're calling.

Here is a link to the memory management documentation.

Carl Norum
Good answer by Carl. One correction: even though `alloc` and `init` usually occur together, `alloc` is the actual method that returns an object you own and must release or autorelease later. The third family of methods that return an object you own is methods that contain `copy`.
Ole Begemann
+1 for @Ole, thanks for the clarification.
Carl Norum