分類(lèi)-Category

分類(lèi)-Category

分類(lèi)的功能

在OC中,我們可以使用分類(lèi)為類(lèi)添加方法,屬性.也可以覆蓋類(lèi)原有的方法,自己添加新的實(shí)現(xiàn).(說(shuō)是覆蓋,其實(shí)不然.在稍后分類(lèi)加載時(shí)間會(huì)解釋原因)

分類(lèi)的結(jié)構(gòu)

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;
    }
};

從源碼可以看出,分類(lèi)是名為 category_t 的結(jié)構(gòu)體類(lèi)型數(shù)據(jù).

category_t的成員

  • instanceMethods:實(shí)例方法
  • classMethods:類(lèi)方法
  • protocols:協(xié)議
  • instanceProperties:實(shí)例屬性
  • _classProperties:類(lèi)屬性

分類(lèi)的加載順序

分析iOS App啟動(dòng)時(shí)的一系列方法,可以看到分類(lèi)的加載規(guī)則.下面是一系列經(jīng)過(guò)的方法

_objc_init ==> map_images ==> map_images_nolock ==> _read_images ==> remethodizeClass ==> attachCategories

_read_images

// Discover classes. Fix up unresolved future classes. Mark bundle classes.

    for (EACH_HEADER) {
        if (! mustReadClasses(hi)) {
            // Image is sufficiently optimized that we need not call readClass()
            continue;
        }

        bool headerIsBundle = hi->isBundle();
        bool headerIsPreoptimized = hi->isPreoptimized();

        classref_t *classlist = _getObjc2ClassList(hi, &count);
        for (i = 0; i < count; i++) {
            Class cls = (Class)classlist[i];
            Class newCls = readClass(cls, headerIsBundle, headerIsPreoptimized);

            if (newCls != cls  &&  newCls) {
                // Class was moved but not deleted. Currently this occurs 
                // only when the new class resolved a future class.
                // Non-lazily realize the class below.
                resolvedFutureClasses = (Class *)
                    realloc(resolvedFutureClasses, 
                            (resolvedFutureClassCount+1) * sizeof(Class));
                resolvedFutureClasses[resolvedFutureClassCount++] = newCls;
            }
        }
    }
 // Discover protocols. Fix up protocol refs.
    for (EACH_HEADER) {
        extern objc_class OBJC_CLASS_$_Protocol;
        Class cls = (Class)&OBJC_CLASS_$_Protocol;
        assert(cls);
        NXMapTable *protocol_map = protocols();
        bool isPreoptimized = hi->isPreoptimized();
        bool isBundle = hi->isBundle();

        protocol_t **protolist = _getObjc2ProtocolList(hi, &count);
        for (i = 0; i < count; i++) {
            readProtocol(protolist[i], cls, protocol_map, 
                         isPreoptimized, isBundle);
        }
    }
 // Discover categories. Only do this after the initial category
    // attachment has been done. For categories present at startup,
    // discovery is deferred until the first load_images call after
    // the call to _dyld_objc_notify_register completes. rdar://problem/53119145
    if (didInitialAttachCategories) {
        for (EACH_HEADER) {
            load_categories_nolock(hi);
        }
    }
    
    // Realize non-lazy classes (for +load methods and static instances)
    for (EACH_HEADER) {
        classref_t const *classlist = hi->nlclslist(&count);
        for (i = 0; i < count; i++) {
            Class cls = remapClass(classlist[i]);
            if (!cls) continue;

            addClassTableEntry(cls);

            if (cls->isSwiftStable()) {
                if (cls->swiftMetadataInitializer()) {
                    _objc_fatal("Swift class %s with a metadata initializer "
                                "is not allowed to be non-lazy",
                                cls->nameForLogging());
                }
                // fixme also disallow relocatable classes
                // We can't disallow all Swift classes because of
                // classes like Swift.__EmptyArrayStorage
            }
            realizeClassWithoutSwift(cls, nil);
        }
    }

從_read_images方法中,我摘抄了部分代碼.從這一部分代碼,我們可以看到類(lèi)的加載順序.

  • Discover classes. Fix up unresolved future classes. Mark bundle classes.

  • Discover protocols. Fix up protocol refs.

  • Discover categories.===> load_categories_nolock但是很明顯.這里有一個(gè)個(gè)判斷值didInitialAttachCategories.通過(guò)源碼看到.這個(gè)值一開(kāi)始為false.所以這時(shí)并未加載分類(lèi).

  • 繼續(xù)往下走.會(huì)發(fā)現(xiàn)有一種情況.就是non-lazy classes會(huì)調(diào)用realizeClassWithoutSwift方法,方法內(nèi)部會(huì)調(diào)用methodizeClass在內(nèi)部使用objc::unattachedCategories.attachToClass 將分類(lèi)與類(lèi)連接上.
    void
    load_images(const char *path __unused, const struct mach_header *mh)
    {
    if (!didInitialAttachCategories && didCallDyldNotifyRegister) {
    didInitialAttachCategories = true;
    loadAllCategories();
    }

       // Return without taking locks if there are no +load methods here.
       if (!hasLoadMethods((const headerType *)mh)) return;
    
       recursive_mutex_locker_t lock(loadMethodLock);
    
       // Discover load methods
       {
           mutex_locker_t lock2(runtimeLock);
           prepare_load_methods((const headerType *)mh);
       }
    
       // Call +load methods (without runtimeLock - re-entrant)
       call_load_methods();
    

    }

    static void loadAllCategories() {
    mutex_locker_t lock(runtimeLock);

       for (auto *hi = FirstHeader; hi != NULL; hi = hi->getNext()) {
           load_categories_nolock(hi);
       }
    

    }

load_categories_nolock

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};
            // 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(_getObjc2CategoryList(hi, &count));
    processCatlist(_getObjc2CategoryList2(hi, &count));
}

從load_categories_nolock方法中摘抄了部分代碼,發(fā)現(xiàn)內(nèi)部調(diào)用了attachCategories.

attachCategories

// 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)" : "");
    }

    /*
     * Only a few classes have more than 64 categories during launch.
     * This uses a little stack, and avoids malloc.
     *
     * Categories must be added in the proper order, which is back
     * to front. To do that with the chunking, we iterate cats_list
     * from front to back, build up the local buffers backwards,
     * and call attachLists on the chunks. attachLists prepends the
     * lists, so the final result is in the expected order.
     */
    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();

    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);
}
  • method_list_t *mlists(方法數(shù)組)
  • property_list_t *proplists(屬性數(shù)組)
  • protocol_list_t *protolists(協(xié)議數(shù)組)

可以看到.在attachCategories方法中.會(huì)加載方法,屬性,協(xié)議.并且.從load_categories_nolock方法中可以看出.先加載實(shí)例方法,再加載類(lèi)方法.也就是說(shuō).是先處理類(lèi)對(duì)象,再處理元類(lèi)對(duì)象.

在attachCategories 中遍歷加載的分類(lèi)列表.將每一個(gè)分類(lèi)中方法,屬性,協(xié)議通過(guò)attachLists方法.將三個(gè)數(shù)組拼接到類(lèi)對(duì)象或者元類(lèi)對(duì)象的對(duì)應(yīng)的 方法,屬性,協(xié)議 列表中.

從attachToClass看分類(lèi)加載時(shí)機(jī)

從源碼可以看出.加載分類(lèi)的時(shí)候.都會(huì)調(diào)用objc::unattachedCategories.attachToClass.我添加了自己的Test類(lèi)做比較.在attachToClass中增加了自己的代碼并添加斷點(diǎn).查看調(diào)用棧

  • 1.Test類(lèi)與分類(lèi)皆實(shí)現(xiàn)了+load方法

  • 2.Test類(lèi)實(shí)現(xiàn)+load方法,Test的分類(lèi)沒(méi)有實(shí)現(xiàn)+load方法

  • 3.Test類(lèi)沒(méi)有實(shí)現(xiàn)+load方法,Test的分類(lèi)實(shí)現(xiàn)+load方法

  • 4.Test類(lèi)沒(méi)實(shí)現(xiàn)+load方法,Test的分類(lèi)也沒(méi)有實(shí)現(xiàn)+load方法

情況1,2結(jié)果:
image-20210518162747394.png

情況3結(jié)果:
image-20210518162840934.png

情況4結(jié)果:
image-20210518162909336.png

可以看出.只要一個(gè)類(lèi)實(shí)現(xiàn)了+load的方法.類(lèi)就會(huì)強(qiáng)制在read_images時(shí)進(jìn)行分類(lèi)加載.

而類(lèi)不實(shí)現(xiàn)+load,分類(lèi)實(shí)現(xiàn)了,則會(huì)在load_images方法進(jìn)行分類(lèi)加載

而類(lèi)與分類(lèi)都不實(shí)現(xiàn)的情況下.則會(huì)在調(diào)用方法時(shí),進(jìn)行類(lèi)的加載.msgSend ===> lookUpImpOrForward

attachLists

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;
            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();
        }
    }

從attachLists中可以看出.在擴(kuò)容方法數(shù)組時(shí),會(huì)將類(lèi)的舊方法往后移,然后通過(guò)for循環(huán)將分類(lèi)的方法填充進(jìn)空出的位置中.所以,如果分類(lèi)有跟本類(lèi)同名方法,并不會(huì)覆蓋原有方法.只是分類(lèi)方法在方法列表中排前,所以msgSend過(guò)程中.會(huì)先被命中.

并且多個(gè)分類(lèi)有同名方法時(shí),加載順序是怎么樣呢?

@interface Test : NSObject
@end

@implementation Test
@end

@interface Test (Test1)
+ (void)test;
@end

@implementation Test (Test1)
+ (void)test {
    NSLog(@"%s",__func__);
}
@end

@interface Test (Test2)
+ (void)test;
@end

@implementation Test (Test2)
+ (void)test {
    NSLog(@"%s",__func__);
}
@end
image-20210518164916835.png

build phases中,在調(diào)換Test1,Test2的順序后.打印出的結(jié)果也不痛.

//當(dāng)Test1在上
TestExtension[60879:1094130] +[Test(Test2) test]
//Test2在上
TestExtension[60935:1095749] +[Test(Test1) test]

分類(lèi)添加屬性

上面看到.雖然category_t中有屬性列表,并無(wú)成員列表.
所以為類(lèi)添加屬性后,由于不存在成員列表.所以也不會(huì)像類(lèi)聲明屬性時(shí),默認(rèn)會(huì)有@synthesize xxxx這一步驟.生成getter,setter方法和成員名成員標(biāo)量.

所以當(dāng)我們直接使用分類(lèi)聲明的屬性時(shí),無(wú)論是取值還是賦值.都會(huì)報(bào)對(duì)應(yīng)的 unrecognized selector sent to instance錯(cuò)誤.

那么,我們想要通過(guò)分類(lèi),為類(lèi)添加屬性,應(yīng)該怎么做呢?

我們可以通過(guò)OC的關(guān)聯(lián)對(duì)象來(lái)完成分類(lèi)為類(lèi)添加屬性的功能.

關(guān)聯(lián)對(duì)象

runtime中,關(guān)聯(lián)對(duì)象允許我們動(dòng)態(tài)的把一個(gè)對(duì)象與某一塊地址動(dòng)態(tài)的關(guān)聯(lián)起來(lái).篇幅太長(zhǎng),這里不做原理的分析.只簡(jiǎn)單寫(xiě)一下怎么完成關(guān)聯(lián)對(duì)象

//Test+Test1.h
#import "Test.h"

NS_ASSUME_NONNULL_BEGIN

@interface Test (Test1)

@property(nonatomic, copy)NSString *testName;

@end

NS_ASSUME_NONNULL_END

//Test+Test1.m
#import "Test+Test1.h"
#import <objc/runtime.h>

@implementation Test (Test1)

- (void)setTestName:(NSString *)testName {
    objc_setAssociatedObject(self, "testName", testName, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSString *)testName {
    return objc_getAssociatedObject(self, "testName");
}

@end

上述就是使用關(guān)聯(lián)對(duì)象,完成分類(lèi)為類(lèi)添加屬性的示例.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,443評(píng)論 6 532
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,530評(píng)論 3 416
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人,你說(shuō)我怎么就攤上這事。” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 176,407評(píng)論 0 375
  • 文/不壞的土叔 我叫張陵,是天一觀(guān)的道長(zhǎng)。 經(jīng)常有香客問(wèn)我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 62,981評(píng)論 1 312
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,759評(píng)論 6 410
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 55,204評(píng)論 1 324
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,263評(píng)論 3 441
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 42,415評(píng)論 0 288
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,955評(píng)論 1 336
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,782評(píng)論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,983評(píng)論 1 369
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,528評(píng)論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,222評(píng)論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 34,650評(píng)論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 35,892評(píng)論 1 286
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,675評(píng)論 3 392
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,967評(píng)論 2 374

推薦閱讀更多精彩內(nèi)容