BaseDataModel示例(1)-创建一个基于BaseDat

2021-04-28  本文已影响0人  fredericoyang

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

1. 基本模型 normal model

@interface User : BaseDataModel

@property (copy, nonatomic, nullable) NSString<Optional> *nick;
@property (strong, nonatomic, nullable) NSNumber<Optional> *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<Optional> *address;
@property (copy, nonatomic, nullable) NSString<Optional> *mobilephone;
@property (copy, nonatomic, nullable) NSString<Optional> *email;

@end

@protocol ContactInfoModel <NSObject>

@end

@interface User : BaseDataModel

@property (copy, nonatomic, nullable) NSString<Optional> *nick;
@property (strong, nonatomic, nullable) NSNumber<Optional> *age;
@property (strong, nonatomic, nullable) ContactInfoModel<Optional> *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));
}

相关

许可

查看原文

上一篇 下一篇

猜你喜欢

热点阅读