oc 中一个典型的字典转模型样板格式

二次信任 提交于 2019-12-06 16:18:29

自己处理数据模型时,此种格式,不管属性是否为空,都可以任意使用,因为使用了排空方法,十分好用,强烈推荐,代码如下:

模型.h文件中:

#import <Foundation/Foundation.h>

@class User;

@interface Status : NSObject

@property (nonatomic,copy) NSString *created_at;

@property (nonatomic,assign) int64_t id;

@property (nonatomic,copy) NSString *text;

@property (nonatomic,copy) NSString *source;

@property (nonatomic,strong) User *user;

//配图数组

@property (nonatomic,strong) NSArray *pic_urls;

@property (nonatomic,strong) Status * retweeted_status;

//配图字符串数组

//@property (nonatomic,strong) NSMutableArray *pic_strs;

 

+ (instancetype)statusWithDict:(NSDictionary *)dict;

 

- (instancetype)initWithDict:(NSDictionary *)dict;

 

@end

 

模型.m文件中:

#import "Status.h"

#import "User.h"

 

@implementation Status

 

- (instancetype)initWithDict:(NSDictionary *)dict

{   

    self = [super init];

    if (self) {

 

[self setValuesForKeysWithDictionary:dict];

 

       // _ids = [NSString stringWithFormat:@"%@",dict[@"id"]];

//        self.created_at = dict[@"created_at"];

//         self.id = dict[@"id"];

//        self.source = dict[@"source"];

//        self.text = dict[@"text"];

//        self.pic_urls = dict[@"pic_urls"];

   //      self.user = [User userWithDict:dict[@"user"]];

       // self.retweeted_status = [Status statusWithDict:dict[@"retweeted_status"]];

        //self.pic_strs = dict[@"pic_strs"];

       

    }

   

    return self;

}

 

+ (instancetype)statusWithDict:(NSDictionary *)dict{

    return [[self alloc] initWithDict:dict];

}

 

- (void)setValue:(nullable id)value forKey:(nonnull NSString *)key{

    if ([key  isEqual: @"user"]) {

        self.user = [User userWithDict:value];

        return;

    }

    

    if ([key isEqualToString:@"retweeted_status"]) {

        self.retweeted_status = [Status statusWithDict:value];

        return;

    }

    [super setValue:value forKey:key];

}

//排空机制:当key value为空时,程序不会崩溃

- (void)setValue:(nullable id)value forUndefinedKey:(nonnull NSString *)key{

    

}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!