Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initWith vs arrayWith in objC?

What are the pros and cons of creating an array (or any other collection using its respective factory method) with

[[NSArray alloc] init]

vs

[NSArray array]

in objective C? It seems like the latter factory method allows us to not worry about memory management, so I was curious if there's any point in ever using alloc + init, though I'm now more interested in all the differences between these two, and why one would choose one over the other.

like image 429
Popcorn Avatar asked Nov 01 '12 03:11

Popcorn


People also ask

What is difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

What is an NSArray?

An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.

What is NSSet in Swift?

NSSet declares the programmatic interface for static sets of distinct objects. You establish a static set's entries when it's created, and can't modify the entries after that. NSMutableSet , on the other hand, declares a programmatic interface for dynamic sets of distinct objects.

Is NSArray ordered?

In Objective-C, arrays take the form of the NSArray class. An NSArray represents an ordered collection of objects. This distinction of being an ordered collection is what makes NSArray the go-to class that it is.


2 Answers

Prior to ARC there was a critical difference. The alloc/init case returned a retained object, while the array case returned an autoreleased object.

With ARC the difference is less important. Probably the first case is a hair more efficient, but in most scenarios they are interchangeable.

like image 128
Hot Licks Avatar answered Sep 20 '22 21:09

Hot Licks


In the first one, you have the ownership of array object & you have to release them.

NSMutableArray* p = [[NSMutableArray alloc] init];

[p release];

& last one you dont need to release as you don't have the ownership of array object.

NSMutableArray* p = [NSMutableArray]; //this is autoreleased

If you call release in this, then it will crash your application.

like image 31
user1535967 Avatar answered Sep 21 '22 21:09

user1535967