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:...的初始化方法,统一来。代码更加统一
     
  • 相关阅读:
    佳佳的 Fibonacci
    毒瘤之神的考验
    An error occurred while searching for implementations of method
    eclipse 开发 scala
    hbase的数据模型
    Hbase和RDBMS(关系数据库管理系统)区别
    hbase和mapreduce开发 WordCount
    使用eclipse开发hbase程序
    hbase 的体系结构
    hbase 遇到过的问题
  • 原文地址:https://www.cnblogs.com/xufengyuan/p/6575863.html
Copyright © 2011-2022 走看看