简体   繁体   English

NSMutableArray的初始化

[英]Initialization of NSMutableArray

When we want to assign some value in NSMutableArray, First of all we have to initialize it. 当我们想在NSMutableArray中分配一些值时,首先我们必须对其进行初始化。

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. 如果您使用的是非ARC项目,则在第一个项目中,您必须拥有数组对象的所有权并必须释放它们。它返回仅保留的对象;第二个项目则返回一个保留且已自动释放的对象。拥有数组对象的所有权。

In ARC code, it doesn't matter which of these you use. 在ARC代码中,使用哪种都无所谓。

Refer ARRAY CLASS and this SO QUESTION 请参阅阵列类和此问题

Alloc : Class method of NSObject. Alloc :NSObject的类方法。 Returns a new instance of the receiving class. 返回接收类的新实例。

Init : Instance method of NSObject. 初始化 :NSObject的实例方法。 Implemented by subclasses to initialize a new object (the receiver) immediately after memory for it has been allocated. 由子类实现,以在为其分配内存后立即初始化一个新对象(接收者)。

New : Class method of NSObject. 新增 :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. 使用+ new的唯一好处是它更加简洁。 If you need to provide arguments to the class's initialiser, you will have to use the +alloc and -initWith... methods instead. 如果需要为类的初始化程序提供参数,则必须使用+ alloc和-initWith ...方法。

  • new doesn't support custom initializers 新不支持自定义初始化程序
  • alloc-init is more explicit than new alloc-init比new更显式

General opinion seems to be that you should use whatever you're comfortable with. 一般认为,您应该使用自己喜欢的任何东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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