zoukankan      html  css  js  c++  java
  • [runtime] initialize方法讲解

    + (void)initialize
    Description(描述)   
    Initializes the class before it receives its first message.

    在这个类第一次接受信息之前初始化这个类.


    The runtime sends initialize to each class in a program just before the class, or any class that inherits from it, is sent its first message from within the program. The runtime sends the initialize message to classes in a thread-safe manner.

    在一个类被第一次调用之前,或者任何从这个类继承的子类第一次调用时,runtime都会初始化这个类.程序会给它发送第一条消息.runtime以线程安全的方式发送了initialize信息.

    Superclasses receive this message before their subclasses. The superclass implementation may be called multiple times if subclasses do not implement initialize—the runtime will call the inherited implementation—or if subclasses explicitly call [super initialize]. If you want to protect yourself from being run multiple times, you can structure your implementation along these lines:

    父类比子类更先收到这个消息.父类也许会被重复调用几次,如果子类并没有实现这个initialize方法.runtime会调用这个继承来的inherited方法.或者,或者子类明确的调用了[super initialize].如果,你想保护你自己,防止被多次调用,你可以用如下的方式来避免:


    + (void)initialize {
      if (self == [ClassName self]) {
        // ... do the initialization ...
      }
    }
    Because initialize is called in a thread-safe manner and the order of initialize being called on different classes is not guaranteed, it’s important to do the minimum amount of work necessary in initialize methods. Specifically, any code that takes locks that might be required by other classes in their initialize methods is liable to lead to deadlocks. Therefore you should not rely on initialize for complex initialization, and should instead limit it to straightforward, class local initialization.
    initialize is invoked only once per class. If you want to perform independent initialization for the class and for categories of the class, you should implement load methods.

    因为initialize方法是以线程安全的方式调用的,所以,不同的类调用了这个initialize是无法保证顺序的.所以,在initialize方法中做最轻量的工作.尤其是,某些锁住的代码,而被另外的一个类所必须使用的,就会照成死锁.所以,所以,你不能指望靠initialize来执行复杂的初始化,且需要用线性的方式来执行.initialize仅仅被执行一次.如果你想实现独立的initialize方法,或者是这个类的类目文件中的方法,你需要实现load方法.

    小结:

    1. initialize每个类只执行一次,是在第一次调用这个类之前执行

    2. 在这个initialize方法中,尽量以线性的方式来执行代码,且需要做轻量级的工作

    3. initialize具有继承树关系,如果继承的子类没有实现initialize方法,那他就会到父类去寻找此方法实现,为了避免多次重复调用这个方法,请添加如下代码

      if (self == [ClassName self]) {
        // ... do the initialization ...
      }

    4. initialize很实用,经常用来封装类中的单例

  • 相关阅读:
    使用Jenkins进行android项目的自动构建(3)
    使用Jenkins进行android项目的自动构建(2)
    使用Jenkins进行android项目的自动构建(1)
    testlink 从1.8.5 升级到 1.9.8
    779. 第K个语法符号(Leetcode)
    687. 最长同值路径(Leetcode)(递归+树)
    116. 飞行员兄弟(Acwing)(递归+位运算)
    95. 费解的开关(Acwing)(分析+递推)
    Java遇到输入速度瓶颈时的解决办法
    92. 递归实现指数型枚举(Acwing)(递归)
  • 原文地址:https://www.cnblogs.com/YouXianMing/p/3658809.html
Copyright © 2011-2022 走看看