淺談 iOS Category 若干問題

如何在 Category 如何調用本類方法

實際上,如果一個類的分類重寫了這個類的方法后,那么這個類的這個方法將失效,起作用的將會是分類的那個重寫方法,在分類重寫的時候 Xcode 也會給出相應警告。

Category is implementing a method which will also be implemented by its primary class

ViewController

@interface ViewController : UIViewController

- (void)test;

@end

@implementation ViewController

- (void)test {
    NSLog(@"ViewController");
}

ViewController + GetSelf

@interface ViewController (GetSelf)

- (void)test;

@end

@implementation ViewController (GetSelf)

- (void)test {
    NSLog(@"ViewController category (GetSelf)");
}

@end

輸出結果:

2019-02-17 22:37:12.972196+0800 CategoryDemo[10142:78261] ViewController category (GetSelf)

實際上,Category 并沒有覆蓋主類的同名方法,只是 Category 的方法排在方法列表前面,而主類的方法被移到了方法列表的后面。
于是,我們可以在 Category 方法里,利用 Runtime 提供的 API,從方法列表里拿回原方法,從而調用。示例:

@interface ViewController (GetSelf)

- (void)test;

@end

@implementation ViewController (GetSelf)

- (void)test {
    NSLog(@"ViewController category (GetSelf)");
    [[CategoryManager shared] invokeOriginalMethod:self selector:_cmd];
}

@end

@interface CategoryManager : NSObject

+ (instancetype)shared;

- (void)invokeOriginalMethod:(id)target selector:(SEL)selector;

@end

@implementation CategoryManager

+ (instancetype)shared {
    static CategoryManager *shareManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareManager = [[CategoryManager alloc] init];
    });
    
    return shareManager;
}

- (void)invokeOriginalMethod:(id)target selector:(SEL)selector {
    // Get the class method list
    uint count;
    Method *methodList = class_copyMethodList([target class], &count);
    
    // Print to console
    for (int i = 0; i < count; i++) {
        Method method = methodList[i];
        NSLog(@"Category catch selector : %d %@", i, NSStringFromSelector(method_getName(method)));
    }
    
    // Call original method . Note here take the last same name method as the original method
    for (int i = count - 1 ; i >= 0; i--) {
        Method method = methodList[i];
        SEL name = method_getName(method);
        IMP implementation = method_getImplementation(method);
        if (name == selector) {
            // id (*IMP)(id, SEL, ...)
            ((void (*)(id, SEL))implementation)(target, name);
            break;
        }
    }
    free(methodList);
}

@end

遍歷 ViewController 類的方法列表,列表里最后一個同名的方法,便是原方法。
原理【load 和 Initialize 加載過程】

Category 中不能動態添加成員變量?

解答:

很多人在面試的時候都會被問到 Category,既然允許用 Category 給類增加方法和屬性,那為什么不允許增加成員變量?
打開 objc 源代碼,在objc-runtime-new.h中我們可以發現:

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;

    method_list_t *methodsForMeta(bool isMeta) {
        if (isMeta) return classMethods;
        else return instanceMethods;
    }

    property_list_t *propertiesForMeta(bool isMeta) {
        if (isMeta) return nil; // classProperties;
        else return instanceProperties;
    }
};

注意:

  • name:是指 class_name 而不是 category_name
  • cls:要擴展的類對象,編譯期間是不會定義的,而是在運行時通過 * name 對應到對應的類對象。
  • instanceMethods:category 中所有給類添加的實例方法的列表。
  • classMethods:category 中所有添加的類方法的列表。
  • protocols:category 實現的所有協議的列表。
  • instanceProperties:category 中添加的所有屬性。

從 category 的定義也可以看出 category 可以添加實例方法,類方法,甚至可以實現協議,添加屬性,無法添加實例變量。

另外在 Objective-C 提供的 runtime 函數中,確實有一個 class_addIvar() 函數用于給類添加成員變量,但是閱讀過蘋果的官方文檔的人應該會看到:

This function may only be called after objc_allocateClassPair and before objc_registerClassPair. Adding an instance variable to an existing class is not supported.

大概的意思說,這個函數只能在“構建一個類的過程中”調用。當編譯類的時候,編譯器生成了一個實例變量內存布局 ivar layout,來告訴運行時去那里訪問類的實例變量們,一旦完成類定義,就不能再添加成員變量了。經過編譯的類在程序啟動后就被 runtime 加載,沒有機會調用 addIvar。程序在運行時動態構建的類需要在調用 objc_registerClassPair 之后才可以被使用,同樣沒有機會再添加成員變量。

Paste_Image.png

從運行結果中看出,你不能為一個類動態的添加成員變量,可以給類動態增加方法和屬性。

因為方法和屬性并不“屬于”類實例,而成員變量“屬于”類實例。我們所說的“類實例”概念,指的是一塊內存區域,包含了 isa 指針和所有的成員變量。所以假如允許動態修改類成員變量布局,已經創建出的類實例就不符合類定義了,變成了無效對象。但方法定義是在 objc_class 中管理的,不管如何增刪類方法,都不影響類實例的內存布局,已經創建出的類實例仍然可正常使用。

同理:

Paste_Image.png

某一個類的分類是在 runTime 時,被動態的添加到類的結構中。
想了解分類是如何加載的請看 iOS RunTime之六:Category

Category 中動態添加的屬性

我們知道在 Category 里面是無法為 Category 添加實例變量的。但是我們很多時候需要在 Category 中添加和對象關聯的值,這個時候可以求助關聯對象來實現。

@interface ViewController (Attribute)

@property (nonatomic, copy) NSString *name;

@end

static char *attributeNameKey;

@implementation ViewController (Attribute)

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

- (NSString *)name {
    return objc_getAssociatedObject(self, &attributeNameKey);
}

@end

可以借助關聯對象來為一個類動態添加屬性,但是關聯對象又是存在什么地方呢? 如何存儲? 對象銷毀時候如何處理關聯對象呢?

void _object_set_associative_reference(id object, void *key, id value, uintptr_t policy) {
    // retain the new value (if any) outside the lock.
    ObjcAssociation old_association(0, nil);
    id new_value = value ? acquireValue(value, policy) : nil;
    {
        AssociationsManager manager;
        AssociationsHashMap &associations(manager.associations());
        disguised_ptr_t disguised_object = DISGUISE(object);
        if (new_value) {
            // break any existing association.
            AssociationsHashMap::iterator i = associations.find(disguised_object);
            if (i != associations.end()) {
                // secondary table exists
                ObjectAssociationMap *refs = i->second;
                ObjectAssociationMap::iterator j = refs->find(key);
                if (j != refs->end()) {
                    old_association = j->second;
                    j->second = ObjcAssociation(policy, new_value);
                } else {
                    (*refs)[key] = ObjcAssociation(policy, new_value);
                }
            } else {
                // create the new association (first time).
                ObjectAssociationMap *refs = new ObjectAssociationMap;
                associations[disguised_object] = refs;
                (*refs)[key] = ObjcAssociation(policy, new_value);
                object->setHasAssociatedObjects();
            }
        } else {
            // setting the association to nil breaks the association.
            AssociationsHashMap::iterator i = associations.find(disguised_object);
            if (i !=  associations.end()) {
                ObjectAssociationMap *refs = i->second;
                ObjectAssociationMap::iterator j = refs->find(key);
                if (j != refs->end()) {
                    old_association = j->second;
                    refs->erase(j);
                }
            }
        }
    }
    // release the old value (outside of the lock).
    if (old_association.hasValue()) ReleaseValue()(old_association);
}

可以看到所有的關聯對象都由 AssociationsManager 管理,而 AssociationsManager 定義如下:

class AssociationsManager {
    // associative references: object pointer -> PtrPtrHashMap.
    static AssociationsHashMap *_map;
public:
    AssociationsManager()   { AssociationsManagerLock.lock(); }
    ~AssociationsManager()  { AssociationsManagerLock.unlock(); }
    
    AssociationsHashMap &associations() {
        if (_map == NULL)
            _map = new AssociationsHashMap();
        return *_map;
    }
};

AssociationsManager 里面是由一個靜態 AssociationsHashMap 來存儲所有的關聯對象的。這相當于把所有對象的關聯對象都存在一個全局 map 里面。而 mapkey 是這個對象的指針地址(任意兩個不同對象的指針地址一定是不同的),而這個 mapvalue 又是另外一個 AssociationsHashMap,里面保存了關聯對象的 kv 對。

void *objc_destructInstance(id obj) 
{
    if (obj) {
        // Read all of the flags at once for performance.
        bool cxx = obj->hasCxxDtor();
        bool assoc = obj->hasAssociatedObjects();

        // This order is important.
        if (cxx) object_cxxDestruct(obj);
        if (assoc) _object_remove_assocations(obj);
        obj->clearDeallocating();
    }

    return obj;
}

runtime 的銷毀對象函數 objc_destructInstance 里面會判斷這個對象有沒有關聯對象,如果有,會調用 _object_remove_assocations 做關聯對象的清理工作。

CategoryExtension 的區別

  • Extension 在編譯期決議,它就是類的一部分,在編譯期和頭文件里的 @interface 以及實現文件里的 @implement 一起形成一個完整的類,它伴隨類的產生而產生,亦隨之一起消亡。Extension 一般用來隱藏類的私有信息,你必須有一個類才能為這個類添加 Extension,所以你無法為系統的類比如 NSString 添加 Extension
  • Category 則完全不一樣,它是在運行期決議的。
  • Extension 可以添加成員變量,而 Category 一般不可以。

總之,就 CategoryExtension 的區別來看,Extension 可以添加成員變量,而 Category 是無法添加成員變量的。因為 Category 在運行期,對象的內存布局已經確定,如果添加實例變量就會破壞類的內部布局。

如果有覺得上述我講的不對的地方歡迎指出,大家多多交流溝通。

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

推薦閱讀更多精彩內容