1

When we want to assign some value in NSMutableArray, First of all we have to initialize it.

We can initialize it in two way. One is

NSMutableArray *arr = [NSMutableArray alloc] init];

and the second is

NSMutableArray *arr = [NSMutableArray array];

Then what is the difference between these two methods? and which is better option to use?

user1954352
  • 1,577
  • 4
  • 14
  • 16
  • 1
    You could goto this [link](http://stackoverflow.com/questions/10474934/how-to-initialize-a-nsmutablearray-in-objective-c) will clear your understanding. – nikhil84 Sep 25 '14 at 12:02
  • possible duplicate of [Difference between \[NSMutableArray array\] vs \[\[NSMutableArray alloc\] init\]](http://stackoverflow.com/questions/5423211/difference-between-nsmutablearray-array-vs-nsmutablearray-alloc-init) – Larme Sep 25 '14 at 12:34
  • With ARC there's essentially no difference, in the vast majority of cases. I'd guess that the first is very slightly more efficient. – Hot Licks Sep 25 '14 at 12:37

2 Answers2

4

If you are using non-ARC project, in the first one, you have the ownership of array object & you have to release them.It returns an object that is only retained.The second one returns a retained and autoreleased object as you don't have the ownership of array objects.

In ARC code, it doesn't matter which of these you use.

Refer ARRAY CLASS and this SO QUESTION

Community
  • 1
  • 1
Rumin
  • 3,787
  • 3
  • 27
  • 30
0

Alloc : Class method of NSObject. Returns a new instance of the receiving class.

Init : Instance method of NSObject. Implemented by subclasses to initialize a new object (the receiver) immediately after memory for it has been allocated.

New : Class method of NSObject. Allocates a new instance of the receiving class, sends it an init message, and returns the initialized object.

alloc goes with init

new = alloc + init

The only benefit to using +new is that it is more concise. If you need to provide arguments to the class's initialiser, you will have to use the +alloc and -initWith... methods instead.

  • new doesn't support custom initializers
  • alloc-init is more explicit than new

General opinion seems to be that you should use whatever you're comfortable with.

Daxesh Nagar
  • 1,405
  • 14
  • 22