views:

50

answers:

2

When adding objects to an NSArray using "initWithObjects" can anyone confirm for me that the items are retained. I am pretty sure they are, but can't find it mentioned anywhere with regards to initWithObjects?

// CREATE DRINKS
Coffee *drink1 = [[Coffee alloc] initWithName:@"Flat White"];
Coffee *drink2 = [[Coffee alloc] initWithName:@"Cappucino"];
Coffee *drink3 = [[Coffee alloc] initWithName:@"Latte"];
Coffee *drink4 = [[Coffee alloc] initWithName:@"Mocha"];
Coffee *drink5 = [[Coffee alloc] initWithName:@"Hot Chocolate"];

// SET ARRAY
NSArray *tempArray = [[NSArray alloc] initWithObjects:drink_1, drink_2, drink_3, drink_4, drink_5, nil];
[self setCoffeeList:tempArray];

// CLEAN UP
[drink_1 release];
[drink_2 release];
[drink_3 release];
[drink_4 release];
[drink_5 release];
[tempArray release];
[super viewDidLoad];

cheers Gary

+3  A: 

initWithObjects retains all items in the array.

initWithObjects: count:

  • (id) initWithObjects: (id*)objects count: (NSUInteger)count; Availability: OpenStep

This is a designated initialiser for the class. Subclasses must override this method. This should initialize the array with count (may be zero) objects. Retains each object placed in the array. Calls -init (which does nothing but maintain MacOS-X compatibility), and needs to be re-implemented in subclasses in order to have all other initialisers work.

Orbit
I don't seem to get that description from Xcode documentation, the docs for initWithObjects:count:(NSSet) mention retain, but not NSArray. I guess as Chuck points out its standard practice and not explicitly mentioned everywhere. Many thanks ...
fuzzygoat
@fuzzygoat: The documentation should not need to specify it again for each method. The generic memory management rule is quite simple and short; any object argument that is to be held on to after the method exits should be retained, unless it is a delegate. Apple's documentation generally only document the few exceptions to this rule (`NSNotificationCenter` observers and `CALayer` delegates).
PeyloW
Thank you, much appreciated.
fuzzygoat
+1  A: 

Objects are expected to take ownership of the things they need to keep around. An array is responsible for its items, therefore it retains them. See the memory management guide for complete details. (No, seriously, read it. You'll thank yourself later when you don't have to ask this question about every class you use and your program isn't crashing every five seconds.)

Chuck
Thank you, I will have another look tonight.
fuzzygoat