iOS进阶

分类与扩展及区别

2019-12-17  本文已影响0人  暴躁的小豆子

分类是什么

Category是Objective-C 2.0之后添加的语言特性,分类、类别其实都是指的Category。Category的主要作用是为已经存在的类添加方法。
Objective-C 中的 Category 就是对装饰模式的一种具体实现。它的主要作用是在不改变原有类的前提下,动态地给这个类添加一些方法。

struct category_t {
    const char *name;//分类名称
    classref_t cls;//宿主类
    struct method_list_t *instanceMethods;//实例方法列表
    struct method_list_t *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);
};

通过分类结构可以知道可以为分类添加那些内容(类方法,实例方法,协议,属性)

注意为类别添加属性时用关联的方式

static char *nameKey = "name";
@implementation NSString (THString)

-(void)setName:(NSString *)name{
    
    objc_setAssociatedObject(self, nameKey, name, OBJC_ASSOCIATION_COPY);
}

-(NSString *)name{
    
    return  objc_getAssociatedObject(self, nameKey);
}
分类做了什么

声明私有方法
分解体积庞大的类文件
把framework的私有方法公开

分类特点

运行时决议:编好分类文件之后,并没有把分类中添加的内容附加到宿主类上,而是运行时通过runtime把分类中的内容添加到宿主类中
给系统类添加分类

源码分析
static void remethodizeClass(Class cls)
{
    category_list *cats;
    bool isMeta;
    runtimeLock.assertLocked();
    //这里拿实例方法的添加逻辑来分析  isMeta = NO
    isMeta = cls->isMetaClass();
    // Re-methodizing: check for more categories
    //获取未整合的所有分类
    if ((cats = unattachedCategoriesForClass(cls, false/*not realizing*/))) {
        if (PrintConnecting) {
            _objc_inform("CLASS: attaching categories to class '%s' %s", 
                         cls->nameForLogging(), isMeta ? "(meta)" : "");
        }
        //将所有的分类拼接到所属的宿主类中
        attachCategories(cls, cats, true /*flush caches*/);        
        free(cats);
    }
}
 //将所有的分类拼接到所属的宿主类中

static void 
attachCategories(Class cls, category_list *cats, bool flush_caches)
{
    if (!cats) return;//分类判空
    if (PrintReplacedMethods) printReplacements(cls, cats);

    bool isMeta = cls->isMetaClass();
  //method_list_t 是二维数组 [[method_t, method_t....],[method_t],[method_t, method_t, method_t,........]]
    // fixme rearrange to remove these intermediate allocations
    method_list_t **mlists = (method_list_t **)
        malloc(cats->count * sizeof(*mlists));
    property_list_t **proplists = (property_list_t **)
        malloc(cats->count * sizeof(*proplists));
    protocol_list_t **protolists = (protocol_list_t **)
        malloc(cats->count * sizeof(*protolists));

    // Count backwards through cats to get newest categories first
    int mcount = 0;
    int propcount = 0;
    int protocount = 0;
    int i = cats->count;//宿主类分类的总数
    bool fromBundle = NO;
    while (i--) {//倒序遍历,最先访问最后编译的分类
       // 获取一个分类
        auto& entry = cats->list[i];
       //获取分类方法列表
        method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
        if (mlist) {
            // 最后编译的分类最先添加到分类数组中
            mlists[mcount++] = mlist;
            fromBundle |= entry.hi->isBundle();
        }
         //获取属性列表
        property_list_t *proplist = 
            entry.cat->propertiesForMeta(isMeta, entry.hi);
        if (proplist) {
            proplists[propcount++] = proplist;
        }
        //获取协议列表
        protocol_list_t *protolist = entry.cat->protocols;
        if (protolist) {
            protolists[protocount++] = protolist;
        }
    }

// 获取宿主类中rw的数据,其中包含宿主类的方法列表信息
    auto rw = cls->data();
//针对分类中有关内存管理方法情况下的一些特殊处理
    prepareMethodLists(cls, mlists, mcount, NO, fromBundle);
/*
rw 代表类
mlists 类的方法列表
attachLists 将mcount个元素的方法列表拼接到rw的methods
*/
    rw->methods.attachLists(mlists, mcount);
    free(mlists);
    if (flush_caches  &&  mcount > 0) flushCaches(cls);

    rw->properties.attachLists(proplists, propcount);
    free(proplists);

    rw->protocols.attachLists(protolists, protocount);
    free(protolists);
}
//将mcount个元素的方法列表拼接到rw的methods
 void attachLists(List* const * addedLists, uint32_t addedCount) {
        if (addedCount == 0) return;

        if (hasArray()) {
            // many lists -> many lists
            uint32_t oldCount = array()->count;//列表中原有的列表总数
            uint32_t newCount = oldCount + addedCount;//拼接之后元素总数
            setArray((array_t *)realloc(array(), array_t::byteSize(newCount)));//根据总数从新分配内存
            array()->count = newCount;//重新设置元素总数
    /*
      内存移动
      [[新元素],...[],[原先的元素],[原先的元素]......]
      宿主类在分类方法后面,故宿主类被分类方法所替代
    */
            memmove(array()->lists + addedCount, array()->lists, 
                    oldCount * sizeof(array()->lists[0]));
 //内存拷贝  
            memcpy(array()->lists, addedLists, 
                   addedCount * sizeof(array()->lists[0]));
        }
        else if (!list  &&  addedCount == 1) {
            // 0 lists -> 1 list
            list = addedLists[0];
        } 
        else {
            // 1 list -> many lists
            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;
            memcpy(array()->lists, addedLists, 
                   addedCount * sizeof(array()->lists[0]));
        }
    }

源码总结

分类中的方法可以替换宿主类中的方法
同名分类方法谁能编译取决于编译顺序(谁后编译谁先执行)
名字相同的分类会引起编译错误

扩展(Extension)

扩展作用:
生成私有属性
生成私有成员变量
生成私有方法

特点

编译时决议
只以声明的形式存在,多数情况下寄生于宿主类的.m中(可以理解为内部的私有声明)
不能为系统类添加扩展

这里也可以作为分类与扩展的区别:
分类是运行时决议,拓展是编译时决议
分类既有声明也有实现,扩展只能声明
分类能为系统类添加分类,扩展则不可以

上一篇 下一篇

猜你喜欢

热点阅读