- new做了三件事情
1.开辟存储空间 + alloc 方法
2.初始化所有的属性(成员变量) - init 方法
3.返回对象的地址
Person *p = [Person new];
// alloc做了什么事情: 1.开辟存储空间 2.将所有的属性设置为0 3.返回当前实例对象的地址
Person *p1 = [Person alloc];
// 1.初始化成员变量, 但是默认情况下init的实现是什么都没有做 2.返回初始化后的实例对象地址
Person *p2 = [p1 init];
// [[Person alloc] init];
// 注意: alloc返回的地址, 和init返回的地址是同一个地址
NSLog(@"p1 = %p, p2 = %p", p1, p2);
// [[Person alloc] init]; == [Person new];
// 建议大家以后创建一个对象都使用 alloc init, 这样可以统一编码格式
Person *p3 = [[Person alloc] init];
new
This method is a combination of alloc and init. Like alloc, it initializes the isa instance variable of the new object so it points to the class data structure. It then invokes the init method to complete the initialization process.可以把new方法拆开如下:
(1)调用类方法+alloc分配存储空间,返回未经初始化的对象Person *p1 = [person alloc];
(2)调用对象方法-init进行初始化,返回对象本身 Person *p2=[p1 init];
(3)以上两个过程整合为一句:Person *p=[[Person alloc] init];
说明:
alloc 与 init合起来称为构造方法,表示构造一个对象alloc 方法为对象分配存储空间,并将所分配这一块区域全部清0.
The isa instance variable of the new instance is initialized to a data structure that describes the class; memory for all other instance variables is set to 0.init方法是初始化方法(构造方法),用来对象成员变量进行初始化,默认实现是一个空方法。
An object isn’t ready to be used until it has been initialized. The init method defined in the NSObject class does no initialization; it simply returns self.所以下面两句的作用是等价的
Person *p1 = [Person new];
Person *p = [[Person alloc] init];
iOS 程序通常使用[[类名 alloc] init] 的方式创建对象,因为这个可以与其他initWithXX:...的初始化方法,统一来。代码更加统一