美文网首页
通过KVC与runtime实现模型数据解析的想法

通过KVC与runtime实现模型数据解析的想法

作者: 顺其自然2017 | 来源:发表于2017-10-10 22:48 被阅读0次

    1.//首先通过runtime的class_copyPropertyList与property_getName函数实现Model对象属性转字符串的功能

    -(NSArray *)propertiesToString:(NSObject*)objc

    {

    u_int count;

    objc_property_t *properties  =class_copyPropertyList([objc class], &count);

    NSMutableArray *propertiesArray = [NSMutableArray arrayWithCapacity:count];

    for (int i = 0; i

    {

    const char* propertyName =property_getName(properties[i]);

    [propertiesArray addObject: [NSString stringWithUTF8String: propertyName]];

    }

    free(properties);

    NSLog(@"%@",propertiesArray);

    return propertiesArray;

    }

    2.//通过KVC键值编码来实现从服务器获取JSON数据后自动给Model对象赋值

    -(BOOL)analysisData:(NSObject *)objcModel  data:(NSData *)data

    {

    NSError *error;

    NSArray * arrayProperties = [self propertiesToString:objcModel];

    NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

    if(error != nil)

    {

    NSLog(@"%@",error.description);

    return false;

    }

    for(int i=0;i

    {

    //通过KVC键值编码给Model赋值

    [objcModel setValue:[dict objectForKey:arrayProperties[i]] forKey:arrayProperties[i]];

    }

    return true;

    }

    相关文章

      网友评论

          本文标题: 通过KVC与runtime实现模型数据解析的想法

          本文链接:https://www.haomeiwen.com/subject/yhobyxtx.html