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

相关推荐
小诸葛的博客1 小时前
istio如何自定义重试状态码
云原生·github·istio
MrLi01041 小时前
在git中同时配置gitcode和github访问权限
git·github·gitcode
小怪兽会微笑1 小时前
如何上传github(解决git的时候输入正确的账号密码,但提示认证失败)
git·github
松哥_ai自动化5 小时前
从抓包GitHub Copilot认证请求,认识OAuth 2.0技术
github·copilot
qianmoQ12 小时前
GitHub 趋势日报 (2025年07月15日)
github
handsomestWei12 小时前
GitHub Jekyll博客本地Win开发环境搭建
github·jekyll·blog博客·windows开发环境
DogDaoDao15 小时前
GitHub开源轻量级语音模型 Vui:重塑边缘智能语音交互的未来
大模型·github·音视频·交互·vui·语音模型·智能语音
一小池勺16 小时前
🚀 Git 如何让文件存在于远程仓库却不被本地追踪?
git·github
小华同学ai16 小时前
惊喜! Github 10k+ star 的国产流程图框架,LogicFlow 能解你的图编辑痛点?
前端·后端·github
mortimer17 小时前
为 Index-TTS 打造一个开箱即用的 Windows 整合包:从环境隔离到依赖难题的解决
人工智能·python·github