OC中的initialize和load

Apple的文档很清楚地说明了initialize和load的区别在于:load是只要类所在文件被引用就会被调用,而initialize是在类或者其子类的第一个方法被调用前调用。所以如果类没有被引用进项目,就不会有load调用;但即使类文件被引用进来,但是没有使用,那么initialize也不会被调用。

它们的相同点在于:方法只会被调用一次。(其实这是相对runtime来说的,后边会做进一步解释)。

文档也明确阐述了方法调用的顺序:父类(Superclass)的方法优先于子类(Subclass)的方法,类中的方法优先于类别(Category)中的方法。

下面是官方给出的说明

+(void)initialize

The runtime sendsinitializeto each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.) The runtime sends the initialize message to classes in a thread-safe manner.Superclasses receive this message before their subclasses.

+(void)load

Theloadmessage is sent to classes and categories that are both dynamically loaded and statically linked, but only if the newly loaded class or category implements a method that can respond.

The order of initialization is as follows:

All initializers in any framework you link to.

All+loadmethods in your image.

All C++ static initializers and C/C++__attribute__(constructor)functions in your image.

All initializers in frameworks that link to you.

In addition:

A class’s+loadmethod is called after all of its superclasses’+loadmethods.

A category+loadmethod is called after the class’s own+loadmethod.

In a custom implementation ofloadyou can therefore safely message other unrelated classes from the same image, but anyloadmethods implemented by those classes may not have run yet.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Apple的文档很清楚地说明了initialize和load的区别在于:load是只要类所在文件被引用就会被调用,...
    落寒z阅读 3,060评论 0 1
  • 云南十四怪,火车没有汽车快,坐汽车从红河到大理,一路绿得让人心动。 初到下关,大雨滂沱,人却是很友好的。等雨停了,...
    锦瑟初浅阅读 4,540评论 14 11
  • 木阳说,她在苏州很孤单,除了她姨,没有什么朋友。 我不知道之前她喜气洋洋的告诉我要结婚后面发生了什么故事,对于她这...
    R先生阅读 4,560评论 2 1
  • 抽象类: 首先要明确,为什么要写一个抽象类,因为,有些东西你还不明确,当子类继承它时,需要对那些不明确的东西进行重...
    李霖神谷阅读 1,417评论 0 0
  • 文/王小马 图/网络精选 这两天重新看了道士下山,忽然发现好像看懂了! 也许是因为经历,也许是因为移情?不得而知…...
    怡儿话书影阅读 3,579评论 0 1