iOS - runtime总结

详细总结一下 Runtime 的核心内容:

1. 消息发送机制

objectivec 复制代码
// 消息发送的基本流程
id objc_msgSend(id self, SEL _cmd, ...) {
    // 1. 获取 isa
    Class cls = object_getClass(self);
    
    // 2. 查找缓存
    IMP imp = cache_getImp(cls, _cmd);
    if (imp) return imp(self, _cmd, ...);
    
    // 3. 方法查找
    imp = lookUpImpOrForward(cls, _cmd);
    
    // 4. 执行方法
    return imp(self, _cmd, ...);
}

2. 类与对象结构

2.1 对象结构

objectivec 复制代码
struct objc_object {
    isa_t isa;  // isa 指针
};

// isa 的位域结构
union isa_t {
    uintptr_t bits;
    struct {
        uintptr_t nonpointer     : 1;  // 是否优化的 isa 指针
        uintptr_t has_assoc      : 1;  // 是否有关联对象
        uintptr_t has_cxx_dtor   : 1;  // 是否有 C++ 析构函数
        uintptr_t shiftcls       : 33; // 类的指针
        // ...其他位域
    };
};

2.2 类结构

objectivec 复制代码
struct objc_class : objc_object {
    Class superclass;
    cache_t cache;             // 方法缓存
    class_data_bits_t bits;    // 类的相关信息
    
    class_rw_t *data() {
        return bits.data();
    }
};

3. 方法缓存机制

objectivec 复制代码
struct cache_t {
    struct bucket_t *_buckets;  // 散列表
    mask_t _mask;              // 容量掩码
    mask_t _occupied;          // 已使用数量
    
    IMP imp(SEL sel) {
        bucket_t *b = buckets();
        mask_t m = mask();
        // 查找方法实现
        return findMethod(b, m, sel);
    }
};

4. 类的加载过程

objectivec 复制代码
void _objc_init(void) {
    // 1. 初始化锁
    runtime_init();
    
    // 2. 读取镜像信息
    map_images();
    
    // 3. 加载类和分类
    load_images();
    
    // 4. 调用 +load 方法
    call_load_methods();
}

void call_load_methods(void) {
    // 1. 按顺序调用类的 +load
    call_class_loads();
    
    // 2. 调用分类的 +load
    call_category_loads();
}

5. 关联对象

objectivec 复制代码
// 关联对象表
struct AssociationsManager {
    static AssociationsHashMap *_map;
    
    void setObject(id object, void *key, id value) {
        // 存储关联对象
    }
    
    id getObject(id object, void *key) {
        // 获取关联对象
    }
};

6. 弱引用机制

objectivec 复制代码
struct weak_table_t {
    weak_entry_t *weak_entries;
    size_t num_entries;
    uintptr_t mask;
    
    void insert(id referent, id *referrer) {
        // 添加弱引用
    }
    
    void remove(id referent) {
        // 移除弱引用
    }
};

7. 自动释放池

objectivec 复制代码
class AutoreleasePoolPage {
    static pthread_key_t const key = AUTORELEASE_POOL_KEY;
    id *next;
    pthread_t const thread;
    AutoreleasePoolPage *child;
    
    void *push() {
        // 压入新的自动释放池
    }
    
    void pop(void *token) {
        // 释放对象
    }
};

8. Method Swizzling

objectivec 复制代码
void method_exchangeImplementations(Method m1, Method m2) {
    if (!m1 || !m2) return;
    
    mutex_locker_t lock(runtimeLock);
    
    IMP imp1 = method_getImplementation(m1);
    IMP imp2 = method_getImplementation(m2);
    
    method_setImplementation(m1, imp2);
    method_setImplementation(m2, imp1);
}

9. 动态方法解析

objectivec 复制代码
void _class_resolveMethod(Class cls, SEL sel) {
    if (! cls->isMetaClass()) {
        // 实例方法解析
        resolveInstanceMethod(cls, sel);
    } else {
        // 类方法解析
        resolveClassMethod(cls, sel);
    }
}

10. 性能优化

objectivec 复制代码
// 1. 方法缓存
static inline IMP cache_getImp(Class cls, SEL sel) {
    cache_key_t key = cache_key(sel);
    return cls->cache.find(key);
}

// 2. isa 优化
inline Class 
objc_object::ISA() {
    assert(!isTaggedPointer()); 
    return (Class)(isa.bits & ISA_MASK);
}

关键特性:

  1. 动态性:运行时决议
  2. 消息发送机制
  3. 方法缓存优化
  4. 类动态加载
  5. 关联对象支持
  6. 弱引用管理
  7. 自动释放池
  8. 方法替换能力
  9. 动态方法解析
  10. 性能优化机制

这些特性使 Objective-C Runtime 成为一个强大而灵活的运行时系统。

相关推荐
YJlio6 小时前
10.2.8 以其他账户运行服务(Running services in alternate accounts):为什么“把服务切到某个用户账号下运行”,本质上是在改变服务的整个安全上下文?
python·安全·ios·机器人·django·iphone·7-zip
pop_xiaoli9 小时前
【iOS】KVC与KVO
笔记·macos·ios·objective-c·cocoa
90后的晨仔10 小时前
《swiftUI进阶 第10章:现代状态管理(iOS 17+)》
ios
sakiko_20 小时前
UIKit学习笔记4-使用UITableView制作滚动视图
笔记·学习·ios·swift·uikit
小锋学长生活大爆炸1 天前
【开源软件】这次iPhone也是用上Claw了 | PhoneClaw
ios·开源软件·iphone·claw
SameX1 天前
独立开发一个把走过的路变成 km² 的 App,聊聊 25m 网格和后台 GPS 的坑
ios
XD7429716361 天前
科技早报晚报|2026年4月30日:Agent 安全壳、浏览器 iOS 测试台与可穿戴数据 API,今天更值得看的 3 个技术机会
科技·ios·开源项目·科技新闻·开发者工具
北京自在科技1 天前
Find Hub App 小更新
android·ios·安卓·findmy·airtag
2501_915921431 天前
HTTPS前端劫持 新一代流量劫持解决方案
前端·网络协议·ios·小程序·https·uni-app·iphone
911hzh1 天前
Flutter WebRTC iOS 原理解析:从 getUserMedia 到 Texture,讲清视频采集、纹理渲染与远端通话链路
flutter·ios·webrtc