Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between arrayWithObjects and initWithObjects?

Can you please explain me exact difference between these two lines?

NSArray *foo = [NSArray arrayWithObjects:@"hai",@"how",@"are",@"you",nil];
NSArray *bar = [[NSArray alloc] initWithObjects:@"hai",@"how",@"are",@"you",nil];
like image 510
Thukaram Avatar asked Jul 19 '11 08:07

Thukaram


3 Answers

arrayWithObjects is "convenience constructor".

It will do:

return [[[NSArray alloc] initWithObjects:@"hai",@"how",@"are",@"you",nil] autorelease]

for you.

It is just a convenience method to get an autoreleased object while improving the readability of the statement. Keep in mind that the fact that the object is autoreleased is a simple convention of the language (not a rule, so you could do differently, but I would not suggest that).

like image 158
sergio Avatar answered Oct 24 '22 05:10

sergio


arrayWithObject returns an autoreleased array so you do not have to worry about releasing it when you don't need it anymore (but if you store it in an instance variable, you should retain it to prevent the autorelease pool from freeing it). initWithObject returns an array with a retain count of 1, i.e. you own the array and you must release it at some point to prevent memory leaks.

You might want to read this guide for more clarification.

like image 8
Tamás Avatar answered Oct 24 '22 07:10

Tamás


You own the second array but not the first.

like image 2
JeremyP Avatar answered Oct 24 '22 05:10

JeremyP