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

iOS 開發之遍歷 Model 屬性並用 Runtime 完善字典賦值

編輯:iOS 開發綜合

上一篇《使用 Runtime 給 Model 類賦值》中介紹了如何在 BaseModel 中統一實作賦值方法,前提條件是字典的 key 必須與實體類的屬性名完全一致。本篇要解決兩個更實際的問題:如何遍歷並列印 Model 的所有屬性值,以及當字典 key 與屬性名不一致時該怎麼辦。

用 Runtime 做映射的價值很明確:省掉幾十行手寫賦值程式碼,後期維護成本大幅降低,開發效率顯著提升。

一、取得 Model 的所有屬性名

遍歷 Model 屬性可不像遍歷字典或陣列那樣一個 for 迴圈就能搞定,得先向 Runtime 要資料。下面的方法回傳當前類的所有屬性名,以陣列形式封裝:

/// 透過運行時獲取當前對象的所有屬性名稱,以陣列形式返回
- (NSArray *)allPropertyNames {
    NSMutableArray *allNames = [NSMutableArray array];

    unsigned int propertyCount = 0;
    objc_property_t *propertys = class_copyPropertyList([self class], &propertyCount);

    for (int i = 0; i < propertyCount; i++) {
        objc_property_t property = propertys[i];
        const char *propertyName = property_getName(property);
        [allNames addObject:[NSString stringWithUTF8String:propertyName]];
    }

    free(propertys);   // class_copyPropertyList 返回的記憶體需要手動釋放
    return allNames;
}

注意 class_copyPropertyList 遵循 copy 規則,用完必須 free,否則就是記憶體洩漏。另外它只回傳在介面中顯式宣告的屬性,分類(Category)中添加的屬性不會出現。

二、根據屬性名生成 Getter 並執行

OC 中屬性的 getter 方法名與屬性名一致,因此生成 selector 非常簡單:

#pragma mark - 透過字符串創建 Getter 方法並返回
- (SEL)creatGetterWithPropertyName:(NSString *)propertyName {
    // OC 中的 get 方法就是屬性本身
    return NSSelectorFromString(propertyName);
}

執行 Getter 需要透過方法簽名。OC Runtime 中,凡是需要傳參或接收返回值的方法呼叫,都要走 NSMethodSignature + NSInvocation 這條路:

- (void)displayCurrentModleProperty {
    NSArray *array = [self allPropertyNames];
    NSMutableString *resultString = [[NSMutableString alloc] init];

    for (int i = 0; i < array.count; i++) {
        SEL getSel = [self creatGetterWithPropertyName:array[i]];

        if ([self respondsToSelector:getSel]) {
            // 取得方法簽名
            NSMethodSignature *signature = [self methodSignatureForSelector:getSel];

            // 由簽名建立調用物件
            NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
            [invocation setTarget:self];
            [invocation setSelector:getSel];

            // 接收返回值
            NSObject *__unsafe_unretained returnValue = nil;
            [invocation invoke];
            [invocation getReturnValue:&returnValue];

            [resultString appendFormat:@"%@\n", returnValue];
        }
    }
    NSLog(@"%@", resultString);
}

在 main 中賦值後呼叫驗證:

BeautifulGirlModel *beautifulGirl = [BeautifulGirlModel modelWithDictionary:data];
[beautifulGirl displayCurrentModleProperty];

執行結果:

三、處理字典 key 與屬性名不一致

後端介面返回的欄位名往往駝峰、下劃線混用,跟我們的屬性命名習慣並不一致。最簡潔的解法是讓每個具體 Model 自己維護一份映射關係。

1. 基類預留映射方法

基類預設回傳 nil,子類需要時重寫並回傳映射字典:

#pragma mark - 返回屬性和字典 key 的映射關係
- (NSDictionary *)propertyMapDic {
    return nil;
}

2. 便利初始化方法中分流

- (instancetype)initWithDictionary:(NSDictionary *)data {
    self = [super init];
    if (self) {
        if ([self propertyMapDic] == nil) {
            [self assginToPropertyWithDictionary:data];        // 直接賦值
        } else {
            [self assginToPropertyWithNoMapDictionary:data];   // 先轉換 key
        }
    }
    return self;
}

3. 依映射關係轉換字典

思路很直白:把 key 換成屬性名的字典,然後複用已有的賦值方法,避免重複實作:

#pragma mark - 根據映射關係給 Model 的屬性賦值
- (void)assginToPropertyWithNoMapDictionary:(NSDictionary *)data {
    NSDictionary *propertyMapDic = [self propertyMapDic];
    NSArray *dicKey = [data allKeys];

    NSMutableDictionary *tempDic =
        [[NSMutableDictionary alloc] initWithCapacity:dicKey.count];

    for (int i = 0; i < dicKey.count; i++) {
        NSString *key = dicKey[i];
        [tempDic setObject:data[key] forKey:propertyMapDic[key]];
    }

    [self assginToPropertyWithDictionary:tempDic];
}

4. 建立子類並重寫映射

// BadBoyModel.h
@interface BadBoyModel : BaseModelObject
@property (nonatomic, copy) NSString *boy1;
@property (nonatomic, copy) NSString *boy2;
@property (nonatomic, copy) NSString *boy3;
@property (nonatomic, copy) NSString *boy4;
@end

// BadBoyModel.m
@implementation BadBoyModel

#pragma mark - 返回屬性和字典 key 的映射關係
- (NSDictionary *)propertyMapDic {
    // key 是待轉換的字典 key,value 是對應的 Model 屬性名
    return @{@"keyBoy1": @"boy1",
             @"keyBoy2": @"boy2",
             @"keyBoy3": @"boy3",
             @"keyBoy4": @"boy4"};
}
@end

5. 測試驗證

// 生成 key 與 Model 屬性不同的字典
NSMutableDictionary *data1 = [[NSMutableDictionary alloc] init];
for (int i = 1; i <= 4; i++) {
    NSString *key   = [NSString stringWithFormat:@"keyBoy%d", i];
    NSString *value = [NSString stringWithFormat:@"我是第%d個壞男孩", i];
    [data1 setObject:value forKey:key];
}

BadBoyModel *badBoyModel = [BadBoyModel modelWithDictionary:data1];
[badBoyModel displayCurrentModleProperty];

執行輸出:

四、小結與擴展方向

至此,Model 基類最基礎的能力基本齊全:字典轉模型、屬性遍歷列印、key 映射。後續可依需求繼續擴充,例如:

· 支援嵌套 Model 與 Model 陣列(判斷屬性型別後遞迴處理);
· 加入基本型別的默認值兜底,避免髒數據導致崩潰;
· 實作 modelToDictionary 反向序列化,方便網路請求與本地快取。

Runtime 的威力在於把「重複勞動」交給機器,但前提是你要清楚它的邊界——哪些屬性會被掃到、記憶體由誰釋放、型別轉換在哪裡失敗,這些細節才是這套封裝能不能上生產環境的關鍵。

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