Objective-C基础学习之new方法实现原理

1.new方法实现原理

  • 完整的创建一个可用的对象:Person *p=[Person new];

  • new方法的内部会分别调用两个方法来完成3件事情:

    • (1)使用alloc方法来分配存储空间(返回分配的对象);
    • (2)使用init方法来对对象进行初始化。
    • (3)返回对象的首地址
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:…的初始化方法,统一来。代码更加统一
    原文作者:WenJim
    原文地址: https://www.jianshu.com/p/09269ce87fc9
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞