iOS runtime映射赋值

//

//  BaseModel.m

//  mShop

//

//  Created by apple on 2016/10/14.

//  Copyright © 2016年 start. All rights reserved.

//

#import "BaseModel.h"

#import <objc/runtime.h>

@implementation BaseModel

-(BOOL)reflectDataFromOtherObject:(NSDictionary *)dic

{

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];

NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];

NSString *propertyType = [[NSString alloc] initWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding];

if ([[dic allKeys] containsObject:propertyName]) {

id value = [dic valueForKey:propertyName];

if (![value isKindOfClass:[NSNull class]] && value != nil) {

if ([value isKindOfClass:[NSDictionary class]]) {

id pro = [self createInstanceByClassName:[self getClassName:propertyType]];

                    [pro reflectDataFromOtherObject:value];

                    [self setValue:pro forKey:propertyName];

                }else{

                    [self setValue:value forKey:propertyName];

                }

            }

        }

    }

free(properties);

return true;

}

-(NSString *)getClassName:(NSString *)attributes

{

NSString *type = [attributes substringFromIndex:[attributes rangeOfString:@"\""].location + 1];

    type = [type substringToIndex:[type rangeOfString:@"\""].location];

return type;

}

-(id) createInstanceByClassName: (NSString *)className {

NSBundle *bundle = [NSBundle mainBundle];

    Class aClass = [bundle classNamed:className];

id anInstance = [[aClass alloc] init];

return anInstance;

}

@end

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券