BaseDataModel示例(1)-创建一个基于BaseDataModel的模型

创建一个基于 BaseDataModel的模型 model based on BaseDataModel

1. 基本模型 normal model

@interface User : BaseDataModel

@property (copy, nonatomic, nullable) NSString *nick;
@property (strong, nonatomic, nullable) NSNumber *age;

@end


@implementation User

+(JSONKeyMapper*)keyMapper
{
    return [[JSONKeyMapper alloc] initWithModelToJSONDictionary:@{
        @"dataID": @"ID",      // dataID用作ID
        @"dataName": @"name"   // dataName用作name
    }];
}

@end

// Test
NSDictionary *dictionary = @{@"ID": @59,
                           @"name": [NSNull null],
                           @"nick": @"Tony",
                            @"age": [NSNull null],
                        @"offline": @true};

NSError *error;
User *model = [[User alloc] initWithDictionary:dictionary error:&error];
if (model) {
    LOG_FORMAT(@"%@", STRING_FORMAT(@"model: %@", model));
}

2. 含嵌套模型 with embed model based on BaseDataModel

@interface ContactInfoModel : BaseDataModel

@property (copy, nonatomic, nullable) NSString *address;
@property (copy, nonatomic, nullable) NSString *mobilephone;
@property (copy, nonatomic, nullable) NSString *email;

@end

@protocol ContactInfoModel 

@end

@interface User : BaseDataModel

@property (copy, nonatomic, nullable) NSString *nick;
@property (strong, nonatomic, nullable) NSNumber *age;
@property (strong, nonatomic, nullable) ContactInfoModel *contactInfo;

@end


@implementation ContactInfoModel

@end

@implementation User

+(JSONKeyMapper*)keyMapper
{
    return [[JSONKeyMapper alloc] initWithModelToJSONDictionary:@{
        @"dataID": @"ID",      // dataID用作ID
        @"dataName": @"name"   // dataName用作name
    }];
}

@end

//Test
NSDictionary *dictionary = @{@"ID": @59,
                           @"name": [NSNull null],
                           @"nick": @"Tony",
                            @"age": [NSNull null],
                    @"contactInfo": @{@"address": [NSNull null],
                                  @"mobilephone": @"136xxxxxxxx",
                                        @"email": [NSNull null]},
                        @"offline": @true};

NSError *error;
User *model = [[User alloc] initWithDictionary:dictionary error:&error];
if (model) {
    LOG_FORMAT(@"%@", STRING_FORMAT(@"model: %@", model));
}

相关

  • 详见极致框架官网的介绍。通过极致框架官网顶部的搜索功能搜索 BaseDataModel。

许可

  • 本文采用 BY-NC-SA 许可协议。即:署名——转载请注明出处;非商业使用;相同方式传播——再分发的文章许可与原文相同。

查看原文

你可能感兴趣的:(BaseDataModel示例(1)-创建一个基于BaseDataModel的模型)