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的执行顺序

相关推荐
至善迎风2 小时前
版本管理系统与平台(权威资料核对、深入解析、行业选型与国产平台补充)
git·gitee·gitlab·github·svm
fengfuyao9853 小时前
诊断并修复SSH连接Github时遇到的“connection closed“错误
运维·ssh·github
NocoBase3 小时前
6 个替代 Jira 的开源项目管理工具推荐
低代码·开源·github
2301_803554524 小时前
github上传步骤
github
ruanCat5 小时前
使用 github workflow 的 actions/setup-node 工作流,安装 pnpm 失败的 bug
github
Moonbit5 小时前
月报Vol.03: 新增Bitstring pattern支持,构造器模式匹配增强
后端·算法·github
先做个垃圾出来………6 小时前
Github操作
github
止观止8 小时前
GitHub自动化利器:Probot框架实战指南
运维·自动化·github
掘我的金9 小时前
galgamex 容器化部署实战:从 Dockerfile、Compose 到 Prisma 初始化与首个账号
github
我的收藏手册10 小时前
性能监控shell脚本编写
前端·git·github