简体   繁体   中英

Initialization of NSMutableArray

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM