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?

3
  • 1
    You could goto this link will clear your understanding. Commented Sep 25, 2014 at 12:02
  • possible duplicate of Difference between [NSMutableArray array] vs [[NSMutableArray alloc] init] Commented Sep 25, 2014 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. Commented Sep 25, 2014 at 12:37

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.