您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

Objective-C Runtime:動態取得任意物件的所有屬性與方法

編輯:iOS 開發綜合

Objective-C 是動態語言,這份彈性有很大一部分來自 Runtime。透過 <objc/runtime.h>,我們可以在執行期走訪一個物件的「結構」:它有哪些屬性、每個屬性的目前值、又實作了哪些方法。這在除錯、日誌記錄、ORM 對映、測試輔助工具等場景中都非常實用。

最方便的切入點,是用 Category 把這些能力掛到 NSObject 上,讓所有物件都具備自省能力。

完整實作

#import <objc/runtime.h>

@implementation NSObject (XXOOProperty)

/* 取得物件的所有屬性及其值 */
- (NSDictionary *)getAllPropertiesAndValues {
    NSMutableDictionary *props = [NSMutableDictionary dictionary];
    unsigned int outCount, i;

    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        const char *char_f = property_getName(property);
        NSString *propertyName = [NSString stringWithUTF8String:char_f];
        id propertyValue = [self valueForKey:(NSString *)propertyName];
        if (propertyValue) {
            [props setObject:propertyValue forKey:propertyName];
        }
    }
    free(properties);
    return props;
}

/* 只取得屬性名稱清單 */
- (NSArray *)getAllProperties {
    u_int count;
    objc_property_t *properties = class_copyPropertyList([self class], &count);
    NSMutableArray *propertiesArray = [NSMutableArray arrayWithCapacity:count];
    for (int i = 0; i < count; i++) {
        const char *propertyName = property_getName(properties[i]);
        [propertiesArray addObject:[NSString stringWithUTF8String:propertyName]];
    }
    free(properties);
    return propertiesArray;
}

/* 取得物件的所有方法 */
- (void)getAllMethods {
    unsigned int mothCout_f = 0;
    Method *mothList_f = class_copyMethodList([self class], &mothCout_f);
    for (int i = 0; i < mothCout_f; i++) {
        Method temp_f = mothList_f[i];
        SEL name_f = method_getName(temp_f);
        const char *name_s = sel_getName(name_f);
        int arguments = method_getNumberOfArguments(temp_f);
        const char *encoding = method_getTypeEncoding(temp_f);
        NSLog(@"方法名:%@, 參數個數:%d, 編碼方式:%@",
              [NSString stringWithUTF8String:name_s],
              arguments,
              [NSString stringWithUTF8String:encoding]);
    }
    free(mothList_f);
}

@end

幾個實作上的關鍵細節

  • class_copyPropertyList 與 class_copyMethodList 都帶有 copy 字樣,代表回傳的是你擁有的記憶體,用完務必 free(),否則就是記憶體洩漏。
  • property_getName 與 sel_getName 回傳的是 C 字串,記得轉成 NSString 再使用。
  • 用 valueForKey: 取值時,若屬性尚未初始化或呼叫 getter 有副作用,要留意可能拋出例外;正式環境建議包一層 @try/@catch。
  • 這裡走訪的是「類別層級」宣告的屬性與方法,不包含 IBOutlet 對應的實例變數(那要用 class_copyIvarList)。

Runtime 的威力很大,但正因為它繞過了編譯期的檢查,錯誤通常不會在編譯時被發現。建議把這類能力集中在診斷工具或開發時期的除錯面板,而不是散落在正式業務流程裡。

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