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

iOS:用 runtime 擴充 NSObject,讓字典直接灌進模型

編輯:iOS 開發綜合

本篇示範如何透過 Objective-C 的 runtime 機制擴充 NSObject,讓任何模型類別都能直接用一個字典完成賦值。這是相當實用的技巧,能省掉大量重複的手動賦值程式碼。

NSObject+Property.h

#import <Foundation/Foundation.h>

@interface NSObject (Property)

- (void)setDataDictionary:(NSDictionary *)dataDictionary;
- (NSDictionary *)dataDictionary;

@end

NSObject+Property.m

#import "NSObject+Property.h"
#import <objc/runtime.h>

@implementation NSObject (Property)

#pragma mark - 公開方法

- (void)setDataDictionary:(NSDictionary *)dataDictionary {
    [self setAttributes:dataDictionary obj:self];
}

- (NSDictionary *)dataDictionary {
    NSArray *properties = [self propertyNames:[self class]];
    return [self propertiesAndValuesDictionary:self properties:properties];
}

#pragma mark - 內部方法

// 由屬性名稱組出 setter 的 selector:name → setName:
- (SEL)getSetterSelWithAttibuteName:(NSString *)attributeName {
    NSString *captial = [[attributeName substringToIndex:1] uppercaseString];
    NSString *setterSelStr = [NSString stringWithFormat:@"set%@%@:",
                              captial, [attributeName substringFromIndex:1]];
    return NSSelectorFromString(setterSelStr);
}

// 依字典內容設定各屬性
- (void)setAttributes:(NSDictionary *)dataDic obj:(id)obj {
    for (id attrbuteName in [dataDic allKeys]) {
        SEL sel = [obj getSetterSelWithAttibuteName:attrbuteName];

        if ([obj respondsToSelector:sel]) {
            id tmpValue = dataDic[attrbuteName];
            id value = [tmpValue isKindOfClass:[NSNull class]] ? nil : tmpValue;

            [obj performSelectorOnMainThread:sel
                                  withObject:value
                               waitUntilDone:[NSThread isMainThread]];
        }
    }
}

// 取得某個類別自身宣告的屬性名稱清單
- (NSArray *)propertyNames:(Class)class {
    NSMutableArray *propertyNames = [NSMutableArray array];

    unsigned int propertyCount = 0;
    objc_property_t *properties = class_copyPropertyList(class, &propertyCount);

    for (unsigned int i = 0; i < propertyCount; i++) {
        objc_property_t property = properties[i];
        const char *name = property_getName(property);
        [propertyNames addObject:[NSString stringWithUTF8String:name]];
    }

    free(properties);
    return propertyNames;
}

// 依屬性清單組出 屬性名稱 → 值 的字典
- (NSDictionary *)propertiesAndValuesDictionary:(id)obj properties:(NSArray *)properties {
    NSMutableDictionary *propertiesDic = [NSMutableDictionary dictionary];

    for (NSString *property in properties) {
        SEL getSel = NSSelectorFromString(property);
        if ([obj respondsToSelector:getSel]) {
            NSString *valueObj = nil;

            NSMethodSignature *signature = [obj methodSignatureForSelector:getSel];
            NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
            [invocation setTarget:obj];
            [invocation setSelector:getSel];

            // 依回傳型別決定怎麼取值,這裡只示範物件型別
            [invocation invoke];
            [invocation getReturnValue:&valueObj];

            if (valueObj) {
                [propertiesDic setObject:valueObj forKey:property];
            }
        }
    }

    return propertiesDic;
}

@end

測試用的模型

LModelItems.h

#import <Foundation/Foundation.h>

@interface LModelItems : NSObject

@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSNumber *age;
@property (nonatomic, strong) NSDictionary *addressDic;
@property (nonatomic, strong) NSArray *eventd;

@end

LModelItems.m

#import "LModelItems.h"

@implementation LModelItems
@end

實際使用

#import "NSObject+Property.h"
#import "LModelItems.h"

@implementation LViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    LModelItems *model = [LModelItems new];

    // 一行完成整個物件的填充
    model.dataDictionary = @{
        @"name"       : @"Lisa",
        @"age"        : @26,
        @"addressDic" : @{@"provinces" : @"北京", @"area" : @"海淀區"},
        @"eventd"     : @[@"first", @"second", @"third"]
    };

    NSLog(@"%@", model.dataDictionary);
    NSLog(@"name=%@", model.name);
    NSLog(@"age=%@", model.age);
    NSLog(@"addressDic=%@", [model.addressDic objectForKey:@"provinces"]);
    NSLog(@"eventd=%@", model.eventd);
}

@end

輸出結果:

{
    addressDic = { area = 海淀區; provinces = 北京; };
    age = 26;
    eventd = ( first, second, third );
    name = Lisa;
}
name=Lisa
age=26
addressDic=北京
eventd=( first, second, third )

這套做法的邊界

核心邏輯其實只有兩段,各自單一職責:一段負責「屬性名稱 → setter selector」的組裝與賦值,另一段負責反向的「屬性 → 值」收集。

但用它之前要知道三件事。第一,class_copyPropertyList 不含父類別的屬性,遇到繼承結構要沿 superclass 遞迴。第二,setter 的型別必須與字典值的型別相符,否則 KVC 會拋例外——實務上常搭配 property_getAttributes 做型別轉換,例如把 NSNumber 轉成模型宣告的 NSString。第三,反向取值那段只示範了物件型別,遇到 int、CGFloat 等基本型別時,getReturnValue: 的用法完全不同,需要另外處理。

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