load加载分析

如果是有两个分类,分别是UIViewController+A和UIViewController+B,他们分别实现自己的load方法,最后load方法方法调用的顺序取决于Build PhasesCompile Sources中类的加载顺序。

代码如下:

UIViewController+A

objective-c 复制代码
@interface UIViewController (A)

+ (void)test;

+ (void)testA;

@end
@implementation UIViewController (A)

+ (void)load {
    NSLog(@"load A");
}

+ (void)test {
    NSLog(@"A");
}

+ (void)testA {
    NSLog(@"testA");
}

@end

UIViewController+B

objectivec 复制代码
@interface UIViewController (B)

+ (void)test;

+ (void)testB;

@end
@implementation UIViewController (B)

+ (void)load {
    NSLog(@"load B");
}

+ (void)test {
    NSLog(@"B");
}

+ (void)testB {
    NSLog(@"testB");
}

@end

ViewController

objective-c 复制代码
#import "ViewController.h"
#import "UIViewController+A.h"
#import "UIViewController+B.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [ViewController test];
    [ViewController testA];
    [ViewController testB];
}

@end	

以上的项目代码和工程配置运行结果如下。

css 复制代码
load B
load A
A
testA
testB

以上结果就是

  1. 先执行B的Load方法,
  2. 之后再执行A的Load方法,
  3. 这时候A和B都有相同的test方法,是只是执行A的test。
  4. 这个时候考虑是不是文件是不是被覆盖了,执行代码[ViewController testA];[ViewController testB];这个时候输出结果是testA和testB,证明文件没有覆盖。只是相同的方法才会被影响,这个影响是上面说的方法调用的顺序取决于Build PhasesCompile Sources中类的加载顺序,最后加载的文件的方法会影响先加载文件的相同方法。

总结:

load方法的执行顺序是受什么影响?

答案:调用的顺序取决于Build PhasesCompile Sources中类的加载顺序

如果两个Category有相同的方法名(UIViewController+A和UIViewController+B都有相同的方法test),这时候执行那个方法呢?

答案:UIViewController+A和UIViewController+B都有相同的方法test,但是调用test方法的时候会调用最后加载的文件的test方法,上面图片的例子只会执行A的test方法。

这个时候有其他的方法,例子:UIViewController+A有testA和UIViewController+B有testB,这个时候会受到影响吗?执行testB会出现找不到方法吗?

答案:不会,文件不是被覆盖了,只有相同的方法才会受到Build PhasesCompile Sources中类的加载顺序影响,不是相同的方法名,他们之间是不会相互影响的。

⚠️待办:自己之后想看的资源

测试项目地址:测试iOS中Category中load的执行顺序

相关推荐
云端奇趣3 小时前
探索 3 个有趣的 GitHub 学习资源库
经验分享·git·学习·github
运营黑客4 小时前
发现一超级Prompt:让GPT-4o、Claude3.5性能再升级(附保姆级教程)
github
記億揺晃着的那天5 小时前
Github优质项目推荐-第二期
github
Uncertainty!!9 小时前
GitHub入门与实践
github
罗曼蒂克在消亡10 小时前
github项目——gpt-pilot自动创建应用
gpt·github·github项目
篝火12 小时前
MindSearch 部署到Github Codespace 和 Hugging Face Space
人工智能·python·github
无限大.1 天前
0基础学前端 day6 -- 搭建github pages静态网址
前端·github
理论最高的吻1 天前
项目配置说明
github
燕雀安知鸿鹄之志哉.2 天前
玄机:第九章-algo
网络·经验分享·安全·web安全·网络安全·github
陈苏同学2 天前
3. 将GitHub上的开源项目导入(clone)到本地pycharm上——深度学习·科研实践·从0到1
python·深度学习·github