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

相关推荐
通义灵码9 小时前
Qoder 支持通过 DeepLink 添加 MCP Server
人工智能·github·mcp
数据大魔方13 小时前
【期货量化实战】跨期套利策略:价差交易完整指南(TqSdk源码详解)
数据库·python·算法·github·程序员创富
数据大魔方15 小时前
【期货量化实战】螺纹钢量化交易指南:品种特性与策略实战(TqSdk完整方案)
python·算法·github·程序员创富·期货程序化·期货量化·交易策略实战
Cx330❀16 小时前
Git 多人协作全攻略:从入门到高效协同
大数据·elasticsearch·搜索引擎·gitee·github·全文检索·gitcode
CoderJia程序员甲18 小时前
GitHub 热榜项目 - 日榜(2026-1-9)
开源·大模型·llm·github·ai教程
lpfasd1231 天前
系统、详细地介绍 GitHub 官方 API 的能力边界
github
KevinShi_BJ1 天前
Github Copilot 实践
github·copilot
秋雨雁南飞1 天前
图床软件 PicGo + Github
github·picgo·图床
moment&forever1 天前
GitHub 托管 API 地址配置文件:实现零成本云配置托管
github
小龙1 天前
【Git 报错解决】本地无有效提交无法推送(`src refspec main does not match any`)
git·github·报错