用字典给Model赋值
生活随笔
收集整理的這篇文章主要介紹了
用字典给Model赋值
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
用字典給Model賦值
此篇教程講述通過runtime擴展NSObject,可以直接用字典給Model賦值,這是相當有用的技術呢。
源碼:
NSObject+Properties.h 與?NSObject+Properties.m
// // NSObject+Properties.m // // Created by YouXianMing on 14-9-4. // Copyright (c) 2014年 YouXianMing. All rights reserved. //#import "NSObject+Properties.h" #import <objc/runtime.h>@implementation NSObject (Properties)#pragma public - 公開方法- (void)setDataDictionary:(NSDictionary*)dataDictionary {[self setAttributes:dataDictionary obj:self]; }- (NSDictionary *)dataDictionary {// 獲取屬性列表NSArray *properties = [self propertyNames:[self class]];// 根據屬性列表獲取屬性值return [self propertiesAndValuesDictionary:self properties:properties]; }#pragma private - 私有方法// 通過屬性名字拼湊setter方法 - (SEL)getSetterSelWithAttibuteName:(NSString*)attributeName {NSString *capital = [[attributeName substringToIndex:1] uppercaseString];NSString *setterSelStr = \[NSString stringWithFormat:@"set%@%@:", capital, [attributeName substringFromIndex:1]];return NSSelectorFromString(setterSelStr); }// 通過字典設置屬性值 - (void)setAttributes:(NSDictionary*)dataDic obj:(id)obj {// 獲取所有的key值NSEnumerator *keyEnum = [dataDic keyEnumerator];// 字典的key值(與Model的屬性值一一對應)id attributeName = nil;while ((attributeName = [keyEnum nextObject])){// 獲取拼湊的setter方法SEL sel = [obj getSetterSelWithAttibuteName:attributeName];// 驗證setter方法是否能回應if ([obj respondsToSelector:sel]){id value = nil;id tmpValue = dataDic[attributeName];if([tmpValue isKindOfClass:[NSNull class]]){// 如果是NSNull類型,則value值為空value = nil;}else{value = tmpValue;}// 執行setter方法[obj performSelectorOnMainThread:selwithObject:valuewaitUntilDone:[NSThread isMainThread]];}} }// 獲取一個類的屬性名字列表 - (NSArray*)propertyNames:(Class)class {NSMutableArray *propertyNames = [[NSMutableArray alloc] init];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 *propertiesValuesDic = [NSMutableDictionary dictionary];for (NSString *property in properties){SEL getSel = NSSelectorFromString(property);if ([obj respondsToSelector:getSel]){NSMethodSignature *signature = nil;signature = [obj methodSignatureForSelector:getSel];NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];[invocation setTarget:obj];[invocation setSelector:getSel];NSObject * __unsafe_unretained valueObj = nil;[invocation invoke];[invocation getReturnValue:&valueObj];//assign to @"" stringif (valueObj == nil){valueObj = @"";}propertiesValuesDic[property] = valueObj;}}return propertiesValuesDic; }@end
測試用Model
Model.h 與?Model.m
// // Model.m // Runtime // // Created by YouXianMing on 14-9-5. // Copyright (c) 2014年 YouXianMing. All rights reserved. //#import "Model.h"@implementation Model@end
使用時的情形
// // AppDelegate.m // Runtime // // Created by YouXianMing on 14-9-5. // Copyright (c) 2014年 YouXianMing. All rights reserved. //#import "AppDelegate.h" #import "NSObject+Properties.h" #import "Model.h"@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {// 初始化modelModel *model = [Model new];// 通過字典賦值model.dataDictionary = @{@"name" : @"YouXianMing",@"age" : @26,@"addressInfo" : @{@"HuBei": @"WeiHan"},@"events" : @[@"One", @"Two", @"Three"]};// 打印出屬性值NSLog(@"%@", model.dataDictionary);return YES; }@end
打印的信息:
2014-09-05 21:03:54.840 Runtime[553:60b] {
? ? addressInfo = ? ? {
? ? ? ? HuBei = WeiHan;
? ? };
? ? age = 26;
? ? events = ? ? (
? ? ? ? One,
? ? ? ? Two,
? ? ? ? Three
? ? );
? ? name = YouXianMing;
}
以下是兩段核心代碼(符合單一職能):
?
總結
以上是生活随笔為你收集整理的用字典给Model赋值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: hibernate(3)对象关联映射
- 下一篇: C#中的泛型化方法的实现