最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Objective-C之Category實現(xiàn)分類示例詳解

 更新時間:2022年08月08日 11:26:10   作者:小橘爺  
這篇文章主要為大家介紹了Objective-C之Category實現(xiàn)分類示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

引言

在寫 Objective-C 代碼的時候,如果想給沒法獲得源碼的類增加一些方法,Category 即分類是一種很好的方法,本文將帶你了解分類是如何實現(xiàn)為類添加方法的。

先說結論,分類中的方法會在編譯時變成 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; // 協(xié)議
    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;
    }
};

這個結構體主要是用來存儲分類中可表現(xiàn)的信息,同時也從側面說明了分類是不能創(chuàng)建實例變量的。

運行時

map_images_nolock 是運行時的開始,同時也決定了編譯順序對分類方法之間優(yōu)先級的影響,后編譯的分類方法會放在先編譯的前面:

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,并依次調(diào)用 load_categories_nolock 方法,實現(xiàn)如下:

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 切是否初始化完成,來決定分類到底附著在哪里,其實現(xiàn)如下:

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) { // 獲取不到主類(可能因為弱鏈接),跳過本次循環(huán)
                // 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()) { // 表示類對象已經(jīng)初始化完畢,會進入合并方法。
                        attachCategories(cls, &lc, 1, ATTACH_EXISTING);
                    } else {
                        objc::unattachedCategories.addForClass(lc, cls);
                    }
                }
                if (cat->classMethods  ||  cat->protocols
                    ||  (hasClassProperties && cat->_classProperties))
                {
                    if (cls->ISA()->isRealized()) { // 表示元類對象已經(jīng)初始化完畢,會進入合并方法。
                        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 方法進行的,對方法、屬性和協(xié)議分別進行附著。需要注意的是,在新版的運行時方法中不是將方法放到 rw 中,而是新創(chuàng)建了一個叫做 rwe 的屬性,目的是為了節(jié)約內(nèi)存,方法的實現(xiàn)如下:

// 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(); // 為 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); // 獲取協(xié)議列表
        if (protolist) {
            if (protocount == ATTACH_BUFSIZ) { // 達到容器的容量上限時進行附著
                rwe->protocols.attachLists(protolists, protocount); // 附著遵守的協(xié)議到類或元類中
                protocount = 0;
            }
            protolists[ATTACH_BUFSIZ - ++protocount] = protolist;
        }
    }
    // 將剩余的方法、屬性和協(xié)議進行附著
    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 方法,其作用是將分類的方法放置到類對象或元類對象中,且放在類和元類對象原有方法的前面,這也是為什么分類和類中如果出現(xiàn)同名的方法,會優(yōu)先調(diào)用分類的,也從側面說明了,原有的類中的方法其實并沒有被覆蓋:

void attachLists(List* const * addedLists, uint32_t addedCount) {
        if (addedCount == 0) return; // 數(shù)量為 0 直接返回
        if (hasArray()) {
            // many lists -> many lists
            uint32_t oldCount = array()->count; // 原有的方法列表的個數(shù)
            uint32_t newCount = oldCount + addedCount; // 合并后的方法列表的個數(shù)
            array_t *newArray = (array_t *)malloc(array_t::byteSize(newCount)); // 創(chuàng)建新的數(shù)組
            newArray->count = newCount;
            array()->count = newCount;
            for (int i = oldCount - 1; i >= 0; i--)
                newArray->lists[i + addedCount] = array()->lists[i]; // 將原有的方法,放到新創(chuàng)建的數(shù)組的最后面
            for (unsigned i = 0; i < addedCount; i++)
                newArray->lists[i] = addedLists[i]; // 將分類中的方法,放到數(shù)組的前面
            free(array()); // 釋放原有數(shù)組的內(nèi)存空間
            setArray(newArray); // 將合并后的數(shù)組作為新的方法數(shù)組
            validate();
        }
        else if (!list  &&  addedCount == 1) { // 如果原本不存在方法列表,直接替換
            // 0 lists -> 1 list
            list = addedLists[0];
            validate();
        } 
        else { // 如果原來只有一個列表,變?yōu)槎鄠€,走這個邏輯
            // 1 list -> many lists
            Ptr<List> oldList = list;
            uint32_t oldCount = oldList ? 1 : 0;
            uint32_t newCount = oldCount + addedCount; // 計算所有方法列表的個數(shù)
            setArray((array_t *)malloc(array_t::byteSize(newCount))); // 分配新的內(nèi)存空間并賦值
            array()->count = newCount;
            if (oldList) array()->lists[addedCount] = oldList; // 將原有的方法,放到新創(chuàng)建的數(shù)組的最后面
            for (unsigned i = 0; i < addedCount; i++) // 將分類中的方法,放到數(shù)組的前面
                array()->lists[i] = addedLists[i]; 
            validate();
        }
    }

以上就是Objective-C實現(xiàn)分類示例詳解的詳細內(nèi)容,更多關于Objective-C分類的資料請關注腳本之家其它相關文章!

相關文章

  • iOS10 適配遠程推送功能實現(xiàn)代碼

    iOS10 適配遠程推送功能實現(xiàn)代碼

    這篇文章主要介紹了iOS10 適配遠程推送功能實現(xiàn)代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-09-09
  • iOS中Runtime的幾種基本用法記錄

    iOS中Runtime的幾種基本用法記錄

    RunTime顧名思義運行時,就是系統(tǒng)在運行的時候的一些機制,最主要的是消息機制。下面這篇文章主要給大家介紹了關于iOS中Runtime的幾種基本用法,文中通過示例代碼介紹的非常詳細,需要的朋友下面隨著小編來一起學習學習吧
    2018-07-07
  • iOS使用自帶的UIViewController實現(xiàn)qq加號下拉菜單的功能(實例代碼)

    iOS使用自帶的UIViewController實現(xiàn)qq加號下拉菜單的功能(實例代碼)

    這篇文章主要介紹了iOS使用自帶的UIViewController實現(xiàn)qq加號下拉菜單的功能(實例代碼),需要的朋友可以參考下
    2017-05-05
  • iOS開發(fā)中使用UIScrollView實現(xiàn)圖片輪播和點擊加載

    iOS開發(fā)中使用UIScrollView實現(xiàn)圖片輪播和點擊加載

    這篇文章主要介紹了iOS開發(fā)中使用UIScrollView實現(xiàn)圖片輪播和點擊加載的方法,代碼基于傳統(tǒng)的Objective-C,需要的朋友可以參考下
    2015-12-12
  • iOS自學筆記之XIB的使用教程

    iOS自學筆記之XIB的使用教程

    本篇文章主要介紹了iOS自學筆記之XIB的使用教程,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-01-01
  • iOS APP實現(xiàn)微信H5支付示例總結

    iOS APP實現(xiàn)微信H5支付示例總結

    這篇文章主要介紹了iOS APP實現(xiàn)微信H5支付示例總結,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-02-02
  • iOS應用設計模式開發(fā)中對簡單工廠和工廠方法模式的運用

    iOS應用設計模式開發(fā)中對簡單工廠和工廠方法模式的運用

    這篇文章主要介紹了iOS應用設計模式開發(fā)中對簡單工廠和工廠方法模式的運用,示例代碼為傳統(tǒng)的Objective-C,需要的朋友可以參考下
    2016-03-03
  • IOS開發(fā)之路--C語言指針

    IOS開發(fā)之路--C語言指針

    指針是C語言的精髓,但是很多初學者往往對于指針的概念并不深刻,以至于學完之后隨著時間的推移越來越模糊,感覺指針難以掌握,本文通過簡單的例子試圖將指針解釋清楚
    2014-08-08
  • iOS touch事件區(qū)分單擊雙擊響應的方法

    iOS touch事件區(qū)分單擊雙擊響應的方法

    如果您的 iPhone 應用里有個 view,既有單擊操作又有雙擊操作。用戶雙擊 view 時,總是先執(zhí)行一遍單擊的操作再執(zhí)行雙擊的操作。所以直接判斷時就會發(fā)現(xiàn)不能直接進入雙擊操作。下面是區(qū)分 touch 事件是單擊還是雙擊的方法,需要的朋友可以參考下
    2016-10-10
  • iOS App開發(fā)中Objective-C使用正則表達式進行匹配的方法

    iOS App開發(fā)中Objective-C使用正則表達式進行匹配的方法

    這篇文章主要介紹了iOS App開發(fā)中Objective-C使用正則表達式進行匹配的方法,文中舉了在iOS中驗證用戶郵箱與手機號的例子,非常實用,匹配需要的朋友可以參考下
    2016-05-05

最新評論

甘肃省| 怀仁县| 台北县| 星座| 红桥区| 望都县| 永春县| 日土县| 衡山县| 商都县| 安顺市| 喀什市| 威远县| 阿拉善左旗| 那坡县| 金坛市| 洪泽县| 通化市| 丰宁| 阜宁县| 宜兰县| 长岛县| 华亭县| 巢湖市| 安平县| 茂名市| 和平县| 明光市| 石柱| 维西| 平泉县| 铁力市| 平湖市| 麻城市| 洪湖市| 开化县| 金秀| 泸西县| 延庆县| 紫金县| 武义县|