Difference between NSArray.array/.new /#[]/alloc-init - ios

There seem to be different methods of instantiating NSArrays (same for NSDictionary and some others).
I know:
[NSArray array]
[NSArray new]
#[]
[[NSArray alloc] init]
For readability reasons I usually stick with [NSArray array], but what is the difference between all those, do they all really do the same?

Results are same for all of them, you get a new empty immutable array. These methods have different memory management implications though. ARC makes no difference in the end, but before ARC you would have to use the right version or send appropriate retain, release or autorelease messages.
[NSArray new], [[NSArray alloc] init] return an array with retain count is 1. Before ARC you would have to release or autorelease that array or you'd leak memory.
[NSArray array], #[] return an already autoreleased array (retain count is 0). If you want it to stick around without ARC you'd have to manually retain it or it would be deallocated when the current autorelease pool gets popped.

[NSArray array] : Create and return an empty array
[NSArray new] : alloc, init and return a NSArray object
#[] : Same as 1.
[[NSArray alloc] init] : Same as 2.
Different between [NSArray array] and [[NSArray alloc] init] is if there are non-ARC:
[NSArray array] is an autorelease object. You have to call retain if you want to keep it. E.g when you return an array.
[[NSArray alloc] init] is an retained object. So you don't have to call retain more if you want keep it.
With ARC, they are same.

Related

NSArray alloc and init

I'm a little confused about NSArray initialization. The confusing thing is we have different init methods to init it, and if I just init it without giving any size and any objects, how compiler knows it object count or size in RAM.
What's the logic/difference behind init method? Can anybody explain it briefly?
Edit:
NSArray *sortedArray = [[NSArray alloc] init];
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"quota" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObject:descriptor];
//How is that possible to modifying to immutable object
sortedArray = [sortedContainers sortedArrayUsingDescriptors:sortDescriptors];
I know the differences between NSArray and NSMutableArray and I'm not looking for the differences. I just wonder how that code can compile/execute without an error.
[[NSArray alloc] init] returns an empty, immutable array. There's nothing surprising about that. What else would you return from a method to mean "no items?"
how compiler knows it object count or size in RAM
The object count is 0. It's empty. Its size in RAM is the size of an empty NSArray. NSArray is an object, so it has some standard objc_object overhead, plus some instance variables for NSArray.
That said, as an implementation detail, Cocoa optimizes this out and always returns the same singleton for all empty NSArray objects. You can demonstrate this with:
NSArray *a = [[NSArray alloc] init];
NSArray *b = [[NSArray alloc] init];
NSLog(#"%p", a);
NSLog(#"%p", b);
if (a == b) { // Pointer equality, not isEqual:
NSLog(#"Same object");
}
So, what is this doing?
NSArray *sortedArray = [[NSArray alloc] init]; // (1)
// ... code that doesn't matter ...
sortedArray = [sortedContainers sortedArrayUsingDescriptors:sortDescriptors]; // (2)
At line 1, you're creating a local pointer variable, sortedArray and pointing it to an empty array (it happens to be a singleton, but that's an optimization detail).
At line 2, you create a completely different NSArray by calling sortedArrayUsingDescriptors:. You then point sortedArray at that object. ARC sees that you're no longer pointing at the empty array, and releases it. (Again, optimization details jump in here and the actual steps may be different, but the effect will be the same.)
The correct code here would be:
// ... Code that sets up sortDescriptors ...
NSArray *sortedArray = [sortedContainers sortedArrayUsingDescriptors:sortDescriptors];
Now, in very modern ObjC, you won't see [[NSArray alloc] init] written out very often. It's easier to write #[] (which is really just syntactic sugar for a method call). But before array literals were added to language, [[NSArray alloc] init] or [NSArray array] were reasonably common.
If you just init NSArray without giving any size and any objects it will remain empty during lifetime. NSArray is immutable
If your question is about NSMutableArray, read here at the SO

NSArray copying after autorelease

I am curious on what happen if I have code like this.
NSArray* myArray = [NSArray alloc]initWithObjects:#"a", #"b", #"c", nil];
[myArray autorelease];
myArray = [otherArray copy];
autorelease would mark the memory to be released at the end of current event loop.
Does that mean [otherArray copy] is released at the end of event loop?
No. When you autorelease objects, the objects are added to the autorelease pool, not the pointer to those objects. You're autoreleasing an array, if you copy another array into that pointer, it will not be affected. You should be using ARC anyway, and not using auto/release.

reinitialize a NSArray

If I've to reinitialize a NSArray with others values, is it right to do this?
NSArray *array = [[NSArray alloc] initWithObjects:obj1, obj2, nil];
// ...
// some code
// ...
array = [[NSArray alloc] initWithObjects:obj3, obj4, nil];
thanks
Yes this is absolutely right. The new object is completely different than the previous. The object pointer now points to a new object and the old one will be released, since you are using ARC.
It is not exactly the same as reinitializing because you throw away the object and getting a new, but NSArray is immutable so this is the only way to "reinitialize" it.
Your code does not re-initialze an NSArray. It just assigns a new object to the variable array. That's fine.
I thinks this code may help you. At least, I thing this may be a suitable solution, especially if you are using ARC:
NSObject *obj1 = [NSNull null];
NSObject *obj2 = [NSNull null];
NSMutableArray *arrayObj = [NSMutableArray arrayWithObjects:obj1, obj2, nil];
[arrayObj removeAllObjects];
arrayObj = [NSMutableArray arrayWithObjects:obj1, obj2, nil];
I hope it helps you :)
you can reinitialize NSArray with same name ,you will not get any error or warning but the latest objects gets replaced with previous objects.The previous objects overwrites. For this you have to use ARC otherwise memory problem will occurs.

NSMutableArray initializing from viewDidLoad

arrayOfElements = [NSMutableArray arrayWithArray:[someObj getArray]];
and
arrayOfElements = [[NSMutableArray alloc] init];
arrayOfElements = [someObj getArray];
What's the difference?
The first arrayOfElements does not seem to lose its objects when it returns count in numberOfRowsInSection:(NSInteger)section, but the second one does. I get EXC_BAD_ACCESS when I do it the second way.
EDIT:
Can I suppose now that this is the best way,
arrayOfElements = [[NSMutableArray alloc] initWithArray:[someObj getArray]];
because I am initializing an array with the contents of whatever will be autorelease'd, and I now have a fully independent array in the current class, that is viewDidLoad, oops sorry, ViewController.
This line creates an NSMutableArray from an existing array
arrayOfElements = [NSMutableArray arrayWithArray:[someObj getArray]];
This combination first creates an NSMutableArray and then instantly discards it replacing it with what is returned by [someObj getArray]
arrayOfElements = [[NSMutableArray alloc] init]; // Create new NSMutableArray
arrayOfElements = [someObj getArray]; // Throw away the newly created array and replace with the result of [someObj getArray]
If you are not using ARC then it is purely by luck that either would work.
In both cases arrayOfElements is being assigned an autorelease'd object - which will be cleared soon (most likely the next runloop). It is only by chance that nothing else has been written over this point of memory which allows one of your implementations to still work.
If you are not using ARC then really you should update your project to be using it will handle a lot of cases like this for you.
You should definitely be using properties (not bare ivars) as this will help reduce memory issues (for non-ARC) and give a more consistent interface to your code.
In your header (or class extension) declare the property like this
#property (nonatomic, strong) NSMutableArray *arrayOfElements;
Now for ARC you can simple do
[self setArrayOfElements:[[someObj getArray] mutableCopy];
for non-ARC you can do
NSMutableArray *array = [[someObj getArray] mutableCopy];
[self setArrayOfElements:array];
[array release]; array = nil;
Also note that getArray is a bad method name.
The use of “get” is unnecessary, unless one or more values are returned indirectly.
Coding Guidelines
When you are adding objects to mutable array from another array, try this:
[arrayOfElements addObjectsFromArray: [someObj getArray]];
If you're not using ARC, you need to make sure its retained.
if (arrayOfElements) {
[arrayOfElements release];
}
arrayOfElements = [[NSMutableArray alloc] initWithArray:[someObj getArray]];

iOS: Difference between NSMutableArray alloc/init and arrayWithObjects:

What is the difference between
NSMutableArray* p = [[NSMutableArray alloc] initWithObjects:...]
and
NSMutableArray* p = [NSMutableArray arrayWithObjects:...]
In the first one, you have the ownership of array object & you have to release them.
NSMutableArray* p = [[NSMutableArray alloc] initWithObjects:...];
[p release];
& last one you dont need to release as you don't have the ownership of array object.
NSMutableArray* p = [NSMutableArray arrayWithObjects:...]; //this is autoreleased
If you call release in this, then it will crash your application.
[NSMutableArray arrayWithObjects:] is the same as [[[NSMutableArray alloc] initWithObjects:] autorelease]
In practice, there is no difference if you're on ARC.
The latter basically is just a shorthand for [[NSMutableArray alloc] initWithObjects: ...], except the returned array is autoreleased (which is important if you're still doing manual reference counting).
What I think the difference is that: initWithObjects is a instance method, and arrayWithObject is a class method.

Resources