淺談 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 中不能動態(tài)添加成員變量?

解答:

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

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 實現(xiàn)的所有協(xié)議的列表。
  • instanceProperties:category 中添加的所有屬性。

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

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

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

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

Paste_Image.png

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

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

同理:

Paste_Image.png

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

Category 中動態(tài)添加的屬性

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

@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

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

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

可以看到所有的關聯(lián)對象都由 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 里面是由一個靜態(tài) AssociationsHashMap 來存儲所有的關聯(lián)對象的。這相當于把所有對象的關聯(lián)對象都存在一個全局 map 里面。而 mapkey 是這個對象的指針地址(任意兩個不同對象的指針地址一定是不同的),而這個 mapvalue 又是另外一個 AssociationsHashMap,里面保存了關聯(lián)對象的 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 的銷毀對象函數(shù) objc_destructInstance 里面會判斷這個對象有沒有關聯(lián)對象,如果有,會調用 _object_remove_assocations 做關聯(lián)對象的清理工作。

CategoryExtension 的區(qū)別

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

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

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

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容