zoukankan      html  css  js  c++  java
  • new方法实现原理

    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:...的初始化方法,统一来。代码更加统一
     
  • 相关阅读:
    html5--6-10 CSS选择器7--伪类选择器
    html5--6-9 CSS选择器6--伪类选择器
    html5--6-8 CSS选择器5
    避开美国全球监控阴影下的问题手机,寻求新伙伴
    DMA过程分析
    混淆
    Missile:双状态DP
    Java抓取网页数据(原网页+Javascript返回数据)
    Binders 与 Window Tokens(窗体令牌)
    编程之美2013 初赛一 A
  • 原文地址:https://www.cnblogs.com/xufengyuan/p/6575863.html
Copyright © 2011-2022 走看看