前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS runtime映射赋值

iOS runtime映射赋值

作者头像
星宇大前端
发布2019-01-15 10:50:08
6100
发布2019-01-15 10:50:08
举报
文章被收录于专栏:大宇笔记大宇笔记大宇笔记

//

//  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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016年12月06日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档