美文网首页
OC中的load和initialize方法

OC中的load和initialize方法

作者: 绍清_shao | 来源:发表于2020-04-03 14:15 被阅读0次

    内容

    • load
    • initialize
    • 参考链接

    load方法

    官方文档说明:

    A class’s +load method is called after all of its superclasses’ +load methods.

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

    main函数之前系统会递归调用,另外需要注意的是:

    1. 方法线程安全
    2. runtime调用 +load 方法前后是加了 objc_autoreleasePoolPush()objc_autoreleasePoolPop()
    3. 按照继承顺序递归调用
    4. 先本类,后分类

    使用场景
    Method Swizzle

    + (void)load {
    Method originalFunc = class_getInstanceMethod([self class], @selector(originalFunc));
    Method swizzledFunc = class_getInstanceMethod([self class], @selector(swizzledFunc));
    
    method_exchangeImplementations(originalFunc, swizzledFunc);
    }
    

    initialize

    官方文档说明:

    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.

    // In Parent.m
    + (void)initialize {
      if (self == [Parent class]) {
      NSLog(@"Initialize Parent, caller Class %@", [self class]);
      }
    }
    

    使用场景
    initialize方法一般用于初始化全局变量或静态变量。

    参考链接

    相关文章

      网友评论

          本文标题:OC中的load和initialize方法

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