Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does NSArray initWithObjects: retain objects?

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

like image 714
fuzzygoat Avatar asked Oct 29 '25 17:10

fuzzygoat


2 Answers

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.

like image 173
Brandon Frohbieter Avatar answered Oct 31 '25 11:10

Brandon Frohbieter


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.)

like image 38
Chuck Avatar answered Oct 31 '25 11:10

Chuck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!