广告
返回顶部
首页 > 资讯 > 移动开发 >Objective-C之Category实现分类示例详解
  • 460
分享到

Objective-C之Category实现分类示例详解

Objective-C分类Category分类 2022-11-13 14:11:35 460人浏览 安东尼
摘要

目录引言编译时运行时引言 在写 Objective-C 代码的时候,如果想给没法获得源码的类增加一些方法,CateGory 即分类是一种很好的方法,本文将带你了解分类是如何实现为类添

引言

在写 Objective-C 代码的时候,如果想给没法获得源码的类增加一些方法,CateGory 即分类是一种很好的方法,本文将带你了解分类是如何实现为类添加方法的。

先说结论,分类中的方法会在编译时变成 category_t 结构体的变量,在运行时合并进主类,分类中的方法会放在主类中方法的前面,主类中原有的方法不会被覆盖。同时,同名的分类方法,后编译的分类方法会“覆盖”先编译的分类方法。

编译时

在编译时,所有我们写的分类,都会转化为 category_t 结构体的变量,category_t 的源码如下:

struct category_t {
    const char *name; // 分类名
    classref_t cls; // 主类
    WrappedPtr<method_list_t, PtrauthStrip> instanceMethods; // 实例方法
    WrappedPtr<method_list_t, PtrauthStrip> claSSMethods; // 类方法
    struct protocol_list_t *protocols; // 协议
    struct property_list_t *instanceProperties; // 属性
    // Fields below this point are not always present on disk.
    struct property_list_t *_classProperties; // 类属性
    method_list_t *methodsFORMeta(bool isMeta) {
        if (isMeta) return classMethods;
        else return instanceMethods;
    }
    property_list_t *propertiesForMeta(bool isMeta, struct header_info *hi);
    protocol_list_t *protocolsForMeta(bool isMeta) {
        if (isMeta) return nullptr;
        else return protocols;
    }
};

这个结构体主要是用来存储分类中可表现的信息,同时也从侧面说明了分类是不能创建实例变量的。

运行时

map_images_nolock 是运行时的开始,同时也决定了编译顺序对分类方法之间优先级的影响,后编译的分类方法会放在先编译的前面:

void 
map_images_nolock(unsigned mhCount, const char * const mhPaths[],
                  const struct Mach_header * const mhdrs[])
{
    ...
    {
        uint32_t i = mhCount;
        while (i--) { // 读取 header_info 的顺序,决定了后编译的分类方法会放在先编译的前面
            const headerType *mhdr = (const headerType *)mhdrs[i];
            auto hi = addHeader(mhdr, mhPaths[i], totalClasses, unoptimizedTotalClasses);
    ...

在运行时,加载分类的起始方法是 loadAllCategories,可以看到,该方法从 FirstHeader 开始,遍历所有的 header_info,并依次调用 load_categories_nolock 方法,实现如下:

static void loadAllCategories() {
    mutex_locker_t lock(runtimeLock);
    for (auto *hi = FirstHeader; hi != NULL; hi = hi->getNext()) {
        load_categories_nolock(hi);
    }
}

load_categories_nolock 方法中,会判断类是不是 stubClass 切是否初始化完成,来决定分类到底附着在哪里,其实现如下:

static void load_categories_nolock(header_info *hi) {
    // 是否具有类属性
    bool hasClassProperties = hi->info()->hasCategoryClassProperties();
    size_t count;
    auto processCatlist = [&](category_t * const *catlist) { // 获取需要处理的分类列表
        for (unsigned i = 0; i < count; i++) {
            category_t *cat = catlist[i];
            Class cls = remapClass(cat->cls); // 获取分类对应的主类
            locstamped_category_t lc{cat, hi};
            if (!cls) { // 获取不到主类(可能因为弱链接),跳过本次循环
                // Category's target class is missing (probably weak-linked).
                // Ignore the category.
                if (PrintConnecting) {
                    _objc_inform("CLASS: IGNORING category \?\?\?(%s) %p with "
                                 "missing weak-linked target class",
                                 cat->name, cat);
                }
                continue;
            }
            // Process this category.
            if (cls->isStubClass()) { // 如果时 stubClass,当时无法确定元类对象是哪个,所以先附着在 stubClass 本身上
                // Stub classes are never realized. Stub classes
                // don't know their metaclass until they're
                // initialized, so we have to add categories with
                // class methods or properties to the stub itself.
                // methodizeClass() will find them and add them to
                // the metaclass as appropriate.
                if (cat->instanceMethods ||
                    cat->protocols ||
                    cat->instanceProperties ||
                    cat->classMethods ||
                    cat->protocols ||
                    (hasClassProperties && cat->_classProperties))
                {
                    objc::unattachedCategories.addForClass(lc, cls);
                }
            } else {
                // First, reGISter the category with its target class.
                // Then, rebuild the class's method lists (etc) if
                // the class is realized.
                if (cat->instanceMethods ||  cat->protocols
                    ||  cat->instanceProperties)
                {
                    if (cls->isRealized()) { // 表示类对象已经初始化完毕,会进入合并方法。
                        attachCategories(cls, &lc, 1, ATTACH_EXISTING);
                    } else {
                        objc::unattachedCategories.addForClass(lc, cls);
                    }
                }
                if (cat->classMethods  ||  cat->protocols
                    ||  (hasClassProperties && cat->_classProperties))
                {
                    if (cls->ISA()->isRealized()) { // 表示元类对象已经初始化完毕,会进入合并方法。
                        attachCategories(cls->ISA(), &lc, 1, ATTACH_EXISTING | ATTACH_METACLASS);
                    } else {
                        objc::unattachedCategories.addForClass(lc, cls->ISA());
                    }
                }
            }
        }
    };
    processCatlist(hi->catlist(&count));
    processCatlist(hi->catlist2(&count));
}

合并分类的方法是通过 attachCategories 方法进行的,对方法、属性和协议分别进行附着。需要注意的是,在新版的运行时方法中不是将方法放到 rw 中,而是新创建了一个叫做 rwe 的属性,目的是为了节约内存,方法的实现如下:

// Attach method lists and properties and protocols from categories to a class.
// Assumes the categories in cats are all loaded and sorted by load order, 
// oldest categories first.
static void
attachCategories(Class cls, const locstamped_category_t *cats_list, uint32_t cats_count,
                 int flags)
{
    if (slowpath(PrintReplacedMethods)) {
        printReplacements(cls, cats_list, cats_count);
    }
    if (slowpath(PrintConnecting)) {
        _objc_inform("CLASS: attaching %d categories to%s class '%s'%s",
                     cats_count, (flags & ATTACH_EXISTING) ? " existing" : "",
                     cls->nameForLogging(), (flags & ATTACH_METACLASS) ? " (meta)" : "");
    }
    
    constexpr uint32_t ATTACH_BUFSIZ = 64;
    method_list_t   *mlists[ATTACH_BUFSIZ];
    property_list_t *proplists[ATTACH_BUFSIZ];
    protocol_list_t *protolists[ATTACH_BUFSIZ];
    uint32_t mcount = 0;
    uint32_t propcount = 0;
    uint32_t protocount = 0;
    bool fromBundle = NO;
    bool isMeta = (flags & ATTACH_METACLASS); // 是否是元类对象
    auto rwe = cls->data()->extAllocIfNeeded(); // 为 rwe 生成分配存储空间
    for (uint32_t i = 0; i < cats_count; i++) { // 遍历分类列表
        auto& entry = cats_list[i];
        method_list_t *mlist = entry.cat->methodsForMeta(isMeta); // 获取实例方法或类方法列表
        if (mlist) {
            if (mcount == ATTACH_BUFSIZ) { // 达到容器的容量上限时
                prepareMethodLists(cls, mlists, mcount, NO, fromBundle, __func__); // 准备方法列表
                rwe->methods.attachLists(mlists, mcount); // 附着方法到主类中
                mcount = 0;
            }
            mlists[ATTACH_BUFSIZ - ++mcount] = mlist; // 将分类的方法列表放入准备好的容器中
            fromBundle |= entry.hi->isBundle();
        }
        property_list_t *proplist =
            entry.cat->propertiesForMeta(isMeta, entry.hi); // 获取对象属性或类属性列表
        if (proplist) {
            if (propcount == ATTACH_BUFSIZ) { // 达到容器的容量上限时进行附着
                rwe->properties.attachLists(proplists, propcount); // 附着属性到类或元类中
                propcount = 0;
            }
            proplists[ATTACH_BUFSIZ - ++propcount] = proplist;
        }
        protocol_list_t *protolist = entry.cat->protocolsForMeta(isMeta); // 获取协议列表
        if (protolist) {
            if (protocount == ATTACH_BUFSIZ) { // 达到容器的容量上限时进行附着
                rwe->protocols.attachLists(protolists, protocount); // 附着遵守的协议到类或元类中
                protocount = 0;
            }
            protolists[ATTACH_BUFSIZ - ++protocount] = protolist;
        }
    }
    // 将剩余的方法、属性和协议进行附着
    if (mcount > 0) {
        prepareMethodLists(cls, mlists + ATTACH_BUFSIZ - mcount, mcount,
                           NO, fromBundle, __func__);
        rwe->methods.attachLists(mlists + ATTACH_BUFSIZ - mcount, mcount);
        if (flags & ATTACH_EXISTING) {
            flushCaches(cls, __func__, [](Class c){
                // constant caches have been dealt with in prepareMethodLists
                // if the class still is constant here, it's fine to keep
                return !c->cache.isConstantOptimizedCache();
            });
        }
    }
    rwe->properties.attachLists(proplists + ATTACH_BUFSIZ - propcount, propcount);
    rwe->protocols.attachLists(protolists + ATTACH_BUFSIZ - protocount, protocount);
}

而真正进行方法附着的 attachLists 方法,其作用是将分类的方法放置到类对象或元类对象中,且放在类和元类对象原有方法的前面,这也是为什么分类和类中如果出现同名的方法,会优先调用分类的,也从侧面说明了,原有的类中的方法其实并没有被覆盖:

void attachLists(List* const * addedLists, uint32_t addedCount) {
        if (addedCount == 0) return; // 数量为 0 直接返回
        if (hasArray()) {
            // many lists -> many lists
            uint32_t oldCount = array()->count; // 原有的方法列表的个数
            uint32_t newCount = oldCount + addedCount; // 合并后的方法列表的个数
            array_t *newArray = (array_t *)malloc(array_t::byteSize(newCount)); // 创建新的数组
            newArray->count = newCount;
            array()->count = newCount;
            for (int i = oldCount - 1; i >= 0; i--)
                newArray->lists[i + addedCount] = array()->lists[i]; // 将原有的方法,放到新创建的数组的最后面
            for (unsigned i = 0; i < addedCount; i++)
                newArray->lists[i] = addedLists[i]; // 将分类中的方法,放到数组的前面
            free(array()); // 释放原有数组的内存空间
            setArray(newArray); // 将合并后的数组作为新的方法数组
            validate();
        }
        else if (!list  &&  addedCount == 1) { // 如果原本不存在方法列表,直接替换
            // 0 lists -> 1 list
            list = addedLists[0];
            validate();
        } 
        else { // 如果原来只有一个列表,变为多个,走这个逻辑
            // 1 list -> many lists
            Ptr<List> oldList = list;
            uint32_t oldCount = oldList ? 1 : 0;
            uint32_t newCount = oldCount + addedCount; // 计算所有方法列表的个数
            setArray((array_t *)malloc(array_t::byteSize(newCount))); // 分配新的内存空间并赋值
            array()->count = newCount;
            if (oldList) array()->lists[addedCount] = oldList; // 将原有的方法,放到新创建的数组的最后面
            for (unsigned i = 0; i < addedCount; i++) // 将分类中的方法,放到数组的前面
                array()->lists[i] = addedLists[i]; 
            validate();
        }
    }

以上就是Objective-C实现分类示例详解的详细内容,更多关于Objective-C分类的资料请关注编程网其它相关文章!

--结束END--

本文标题: Objective-C之Category实现分类示例详解

本文链接: https://www.lsjlt.com/news/172074.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Objective-C之Category实现分类示例详解
    目录引言编译时运行时引言 在写 Objective-C 代码的时候,如果想给没法获得源码的类增加一些方法,Category 即分类是一种很好的方法,本文将带你了解分类是如何实现为类添...
    99+
    2022-11-13
    Objective-C分类 Category分类
  • C++实现日期类的示例详解
    目录一、获取某年某月的天数二、Date的默认成员函数(全缺省的默认构造)三、运算符重载1.+ =、+、- =、-2.==、!=、>、>=、<、<=3.前置++...
    99+
    2023-02-07
    C++实现日期类 C++常见日期类 C++日期类
  • C#实现HTTP访问类HttpHelper的示例详解
    在项目开发过程中,我们经常会访问第三方接口,如我们需要接入的第三方接口是Web API,这时候我们就需要使用HttpHelper调用远程接口了。示例中的HttpHelper类使用Lo...
    99+
    2022-11-13
  • 基于Pytorch实现分类器的示例详解
    目录Softmax分类器定义训练测试感知机分类器定义训练测试本文实现两个分类器: softmax分类器和感知机分类器 Softmax分类器 Softmax分类是一种常用的多类别分类算...
    99+
    2023-05-16
    Pytorch实现分类器 Pytorch分类器
  • c#实现flv解析详解示例
    下面是一个使用C#实现FLV解析的示例代码:```csharpusing System;using System.IO;public...
    99+
    2023-08-16
    C#
  • C++实现AVL树的示例详解
    目录AVL 树的概念AVL 树的实现节点的定义接口总览插入旋转AVL 树的概念 也许因为插入的值不够随机,也许因为经过某些插入或删除操作,二叉搜索树可能会失去平衡,甚至可能退化为单链...
    99+
    2023-03-03
    C++实现AVL树 C++ AVL树
  • C++实现LeetCode之区间的示例分析
    这篇文章将为大家详细讲解有关C++实现LeetCode之区间的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。[LeetCode] 228.Summary Ranges 总结区间Given a so...
    99+
    2023-06-20
  • C#实现文件分割和合并的示例详解
    目录实践过程效果代码实践过程 效果 代码 public partial class frmSplit : Form { public frmSplit() { ...
    99+
    2022-12-26
    C#文件分割 合并 C#文件分割 C#文件合并
  • C语言实现栈的示例详解
    目录前言一. 什么是栈二. 使用什么来实现栈三. 栈的实现3.1 头文件3.2 函数实现3.3 完整代码四. 栈的用处前言 前一段时间,我们试着用C语言实现了数据结构中的顺序表,单链...
    99+
    2022-11-13
  • 详解elasticsearch之metric聚合实现示例
    目录1、背景2、准备数据2.1 准备mapping2.2 准备数据3、metric聚合3.1 max 平均值3.1.1 dsl3.1.2 java代码3.2 min最小值3.2.1 ...
    99+
    2023-01-16
    elasticsearch metric聚合 elasticsearch metric
  • C#实现接口base调用示例详解
    目录背景方法1:使用反射找到接口实现并进行调用方法2:利用函数指针方法3:利用Fody在编译时对接口方法进行IL的call调用性能测试总结背景 在三年前发布的C#8.0中有一项重要的...
    99+
    2022-11-13
  • C++实现优先队列的示例详解
    目录前言堆的存储方式维护堆的方法1、上浮操作2、下沉操作附上代码前言 首先,啊,先简单介绍一下优先队列的概念,学数据结构以及出入算法竞赛的相信都对队列这一数据结构十分熟悉,这是一个线...
    99+
    2022-11-13
  • C语言实现队列的示例详解
    目录前言一. 什么是队列二. 使用什么来实现栈三. 队列的实现3.1头文件3.2 函数的实现四.完整代码前言 前一段时间,我们试着用C语言实现了数据结构中的顺序表,单链表,双向循环链...
    99+
    2022-11-13
  • C++实现贪心算法的示例详解
    目录区间问题区间选点最大不相交区间数量区间分组区间覆盖Huffman树合并果子排序不等式排队打水绝对值不等式货舱选址区间问题 区间选点 给定 N 个闭区间 [ai,bi],请你在数轴...
    99+
    2022-11-13
  • C语言实现阶乘的示例详解
    目录前言1.阶乘实现1.1理论步骤1.2实践结果2.连续乘层相加实现2.1理论步骤2.2实践结果前言 在现实中,我们做数学题总会遇到阶乘问题,这在计算机中也不例外。 那我们应该怎么实...
    99+
    2022-11-13
  • C++实现LeetCode之神奇字典的示例分析
    这篇文章将为大家详细讲解有关C++实现LeetCode之神奇字典的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。[LeetCode] 676.Implement Magic Dictionary ...
    99+
    2023-06-20
  • C++实现LeetCode之替换单词的示例分析
    这篇文章主要介绍C++实现LeetCode之替换单词的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完![LeetCode] 648.Replace Words 替换单词In English, we have a...
    99+
    2023-06-20
  • C++实现LeetCode之岛屿数量的示例分析
    这篇文章主要为大家展示了“C++实现LeetCode之岛屿数量的示例分析”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“C++实现LeetCode之岛屿数量的示例分析”这篇文章吧。[LeetCod...
    99+
    2023-06-20
  • C++实现LeetCode之包围区域的示例分析
    这篇文章将为大家详细讲解有关C++实现LeetCode之包围区域的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。[LeetCode] 130. Surrounded Regions 包围区域Giv...
    99+
    2023-06-20
  • C++实现LeetCode之缺失区间的示例分析
    这篇文章给大家分享的是有关C++实现LeetCode之缺失区间的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。[LeetCode] 163. Missing Ranges 缺失区间Given a sort...
    99+
    2023-06-20
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作