您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

objc_runtime 四個實用範例:動態屬性、方法置換與協議檢查

編輯:iOS 相關資訊

Objective-C Runtime 是這門語言最有意思也最危險的部分。下面用四個實際例子說明常見用法。

一、為現有類別動態加上屬性

Category 無法直接加入實例變數,但可以用關聯物件(Associated Object)繞過這個限制。以幫 UIWebView 加上資源計數為例:

// .h
@interface UIWebView (LoadProgress)
@property (nonatomic, assign) NSInteger resourceCount;
@end
// .m
// 關聯物件用的 key,必須是靜態且唯一的位址
static void *s_resourceCountKey = &s_resourceCountKey;

@implementation UIWebView (LoadProgress)
@dynamic resourceCount;

- (NSInteger)resourceCount
{
    NSNumber *count = objc_getAssociatedObject(self, s_resourceCountKey);
    return count ? [count integerValue] : 0;
}

- (void)setResourceCount:(NSInteger)rCount
{
    objc_setAssociatedObject(self, s_resourceCountKey,
                             [NSNumber numberWithInteger:rCount],
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end

使用起來就跟原生屬性一模一樣:

webView.resourceCount = 10;

幾個重點:key 一定要用 static void * 取自身位址,若用字串字面值當 key,不同編譯單元可能產生不同的位址而對不上;@dynamic 是告訴編譯器「getter / setter 我會自己寫」;關聯策略要依型別選擇,物件用 OBJC_ASSOCIATION_RETAIN_NONATOMIC,基本型別用 ASSIGN, NSString 之類建議用 COPY。

二、動態加上協議實作

屬性可以這樣加,協議方法本質上也是方法,同樣能用 method_exchangeImplementations 或 class_addMethod 掛上去。這裡先不展開,思路與第三點的方法置換一致。

三、置換類別方法與實例方法(Swizzling)

Method Swizzling 是 runtime 最常被使用的技巧,用於 AOP 埋點、hack 系統行為、修補第三方元件。下面是兩個通用工具函式:

// 置換類別方法(來源:CoconutKit)
IMP HLSSwizzleClassSelector(Class clazz, SEL selector, IMP newImplementation)
{
    Class metaClass = objc_getMetaClass(class_getName(clazz));
    Method method = class_getClassMethod(metaClass, selector);
    IMP origImp = method_getImplementation(method);
    if (!origImp) return NULL;

    class_replaceMethod(metaClass, selector, newImplementation,
                        method_getTypeEncoding(method));
    return origImp;
}

// 置換實例方法
IMP HLSSwizzleSelector(Class clazz, SEL selector, IMP newImplementation)
{
    Method method = class_getInstanceMethod(clazz, selector);
    IMP origImp = method_getImplementation(method);
    if (!origImp) return NULL;

    class_replaceMethod(clazz, selector, newImplementation,
                        method_getTypeEncoding(method));
    return origImp;
}

要保留原方法以便日後呼叫,先宣告兩個 C 函式指標:

// 原始實作
static id (*s_UIWebView__identifierForInitialRequest_Imp)(id, SEL, id, id, id) = NULL;

// 新的實作
static id swizzled_UIWebView__identifierForInitialRequest_Imp(UIWebView *self, SEL _cmd,
                                                              id webView,
                                                              id initialRequest,
                                                              id dataSource);

交換動作必須寫在 +load 中,確保在任何訊息送達之前就完成:

+ (void)load
{
    s_UIWebView__identifierForInitialRequest_Imp =
        (id (*)(id, SEL, id, id, id))HLSSwizzleSelector(
            self,
            @selector(webView:identifierForInitialRequest:fromDataSource:),
            (IMP)swizzled_UIWebView__identifierForInitialRequest_Imp);
}

新的實作裡先呼叫原方法,再插入自己的邏輯:

#pragma mark Swizzled method implementations

static id swizzled_UIWebView__identifierForInitialRequest_Imp(UIWebView *self, SEL _cmd,
                                                              id webView,
                                                              id initialRequest,
                                                              id dataSource)
{
    // 呼叫原方法
    (*s_UIWebView__identifierForInitialRequest_Imp)(self, _cmd, webView,
                                                    initialRequest, dataSource);

    [self setResourceCount:self.resourceCount + 1];

    return [NSNumber numberWithInteger:self.resourceCount];
}

這樣一來,每次 UIWebView 發出請求時,resourceCount 就會自動累加,可以用來判斷頁面所有資源是否載入完畢。

四、檢查物件是否實作了某協議

可以做成 NSObject 的 Category:

// 來源:CoconutKit
// 用法:[self implementsProtocol:@protocol(UIActionSheetDelegate)]
- (BOOL)implementsProtocol:(Protocol *)protocol
{
    // 只關心 optional 方法,required 方法在編譯期就會被檢查
    unsigned int numberOfMethods = 0;
    struct objc_method_description *methodDescriptions =
        protocol_copyMethodDescriptionList(protocol, NO /* optional only */, YES,
                                            &numberOfMethods);

    for (unsigned int i = 0; i < numberOfMethods; ++i) {
        struct objc_method_description methodDescription = methodDescriptions[i];
        SEL selector = methodDescription.name;

        if (!class_getInstanceMethod([self class], selector)) {
            NSString *selectorString = [NSString stringWithCString:sel_getName(selector)
                                                          encoding:NSUTF8StringEncoding];
            NSString *protocolName   = [NSString stringWithCString:protocol_getName(protocol)
                                                          encoding:NSUTF8StringEncoding];
            NSLog(@"Class %@ does not implement method %@ of protocol %@",
                  NSStringFromClass([self class]), selectorString, protocolName);
            return NO;
        }
    }

    return YES;
}

這個方法在除錯「delegate 怎麼呼叫都沒反應」時特別好用——通常就是某個 optional 方法名稱打錯了一個字。

使用 runtime 的注意事項

最後必須強調幾點風險。第一,Swizzling 修改的是全 App 全域行為,多個第三方套件同時 swizzle 同一個方法時,執行順序難以預期,容易造成難以追查的 bug,建議在交換時呼叫 dispatch_once 確保只做一次,並保留原實作鏈。第二,這裡範例中的 UIWebView 相關私有方法 signature 並非公開 API,用在送審版本有被拒的風險。第三,若只是為了計數或埋點,优先考虑 iOS 12 之後提供的 method_setImplementation 搭配 objc_setAssociatedObject 的組合,會比直接改 IMP 更容易維護。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved