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.
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.
An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With