load加载分析

如果是有两个分类,分别是UIViewController+A和UIViewController+B,他们分别实现自己的load方法,最后load方法方法调用的顺序取决于Build Phases 中Compile 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 Phases 中Compile Sources中类的加载顺序,最后加载的文件的方法会影响先加载文件的相同方法。

总结:

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

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

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

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

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

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

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

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

相关推荐
怕浪猫3 小时前
全球 3D 网络地球的实时通信节点,来看看这四种交互地球,满足你对物理互联网的所有好奇
面试·架构·github
wflynn5 小时前
GitHub 今日推荐|kiri:clone3 系统调用直达容器,2.5 毫秒启动无 runc 中间层
docker·rust·kubernetes·开源·github·containers
可乐ea6 小时前
MCP 和 CLI 差 42 倍:一次 GitHub 任务的上下文成本实测
人工智能·github·工具调用·ai智能体·openrouter·mcp协议·上下文优化
逛逛GitHub7 小时前
Claude 最新模型发布 1 周了,瞧瞧外网惊艳到震撼的玩法。
github
逛逛GitHub7 小时前
最近逛 GitHub 挑了 8 个刚开源、Star 涨得挺快的项目。
github
dong_junshuai8 小时前
每天一个开源项目#158 AG-UI:让Agent事件流接上前端状态
github
吴长建先生重名了10 小时前
一个任务调度系统崩溃 Bug 从性能压测中暴露的真相
github
一条Go13 小时前
Webhook 签名:钉钉、企业微信、飞书的四种算法差异
后端·架构·github
一条Go13 小时前
开源新生代雷达 · 第 12 期
github
徐小夕15 小时前
CADViewer-Skill:让 Agent 原生支持 DWG 解析、可视化图统计、图纸导出
前端·vue.js·github