zoukankan      html  css  js  c++  java
  • NSObject中类方法load/initialize加载时机和作用

    方法调用时机

    相同点: 程序启动都只会执行仅且一次,再次怎么调用使用类都不会执行了.

    不同点: 方法调用时机不一样.

    > + load程序启动类加载时就会调用,不管该类是否有使用或有Import都会执行

    > + initialize 程序启动后,只有类使用时都会触发,包括调用类的类方法或对象方法; 包括该类的创建对象,创建对象在调用类方法alloc, 比如:[Drvier class]同样会触发

    测试实例

    有一个ViewController,

    .touchesBegan,触发Car的类方法和对象方法

    .点击其中一个按钮跳转至ViewControllerSecond控制器

    touchesBegan:

    // 交换类方法
        Method run1 = class_getClassMethod([Car class], @selector(run1));
        Method play1 = class_getClassMethod([Car class], @selector(play1));
        method_exchangeImplementations(play1, run1);
        [Car run1];
        [Car play1];
        
        Car *car = [[Car alloc] init];
        [car run];
        [car play];
        
        // 交换对象方法
        Method run = class_getInstanceMethod([Car class], @selector(run));
        Method play = class_getInstanceMethod([Car class], @selector(play));
        method_exchangeImplementations(play, run);
        
        [car run];
        [car play];
        
        Car *car2 = [[Car alloc] init];
        [car2 run];
        [car2 play];
        
        [Car run1];
        [Car play1];

    程序启动后控制台打印

    2017-09-09 17:09:33.865 Runtime[9060:228475] +[ViewControllerBase load]
    2017-09-09 17:09:33.866 Runtime[9060:228475] +[ViewControllerSecond load]
    2017-09-09 17:09:33.867 Runtime[9060:228475] +[ViewController load]
    2017-09-09 17:09:33.867 Runtime[9060:228475] +[Driver load]
    2017-09-09 17:09:33.867 Runtime[9060:228475] +[Car load]
    2017-09-09 17:09:33.921 Runtime[9060:228475] +[ViewControllerBase initialize]
    2017-09-09 17:09:33.922 Runtime[9060:228475] +[ViewController initialize]

    touches后Car的initialize会调用:

    +[Car initialize]

    点击按钮后:

    +[ViewControllerSecond initialize]

     返回ViewControllerSecond,再次跳转至ViewControllerSecond initialize不会调用了

    应用:

    + load: .比如使用runtime交换方法实现时,可以在此方法中处理; 

    + initialize: .类使用时可以初始化类的一些基础数据;  

  • 相关阅读:
    从零自学Hadoop(15):Hive表操作
    从零自学Hadoop(14):Hive介绍及安装
    从零自学Hadoop(13):Hadoop命令下
    从零自学Hadoop(12):Hadoop命令中
    angularjs不同页面间controller传参方式,使用service封装sessionStorage
    angularjs简单实现$http.post(CORS)跨域及$http.post传参方式模拟jQuery.post
    angularjs中的绑定策略“@”,“=”,“&”实例
    angularjs中ng-repeat-start与ng-repeat-end用法实例
    关于JavaScript对象的键和值
    angularjs中ng-attr的用法
  • 原文地址:https://www.cnblogs.com/HJiang/p/7498719.html
Copyright © 2011-2022 走看看