美文网首页
iOS +initialize

iOS +initialize

作者: SnoopPanda | 来源:发表于2020-05-11 14:10 被阅读0次
官方文档
Initializes the class before it receives its first message.
当类收到第一个消息的时候调用

Discussion

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. Superclasses receive this message before their subclasses.

The runtime sends the `initialize` message to classes in a thread-safe manner. That is, `initialize` is run by the first thread to send a message to a class, and any other thread that tries to send a message to that class will block until `initialize` completes.

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:

Because `initialize` is called in a blocking manner, it’s important to limit method implementations to the minimum amount of work necessary possible. 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.

Special Considerations

`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`](https://developer.apple.com/documentation/objectivec/nsobject/1418815-load?language=objc) methods.
Demo验证
image.png

1.+initialize 在类收到第一个消息时候调用
2.分类重写+initialize会覆盖主类的实现,多个分类只执行最后编译的分类
3.如果子类没有重写+initialize,则会调用父类的+initialize
4.由于+intialize可以被多次调用,要保证不被多次调用可以使用下面的写法

+ (void)initialize {
  if (self == [SomeClass self]) {
    // ... do the initialization ...
  }
}

相关文章

网友评论

      本文标题:iOS +initialize

      本文链接:https://www.haomeiwen.com/subject/gyaynhtx.html