model的属性名映射到其他key
比较常用,比如将模型中的属性名"ID"映射到json中的"id"
+ (NSDictionary *)modelCustomPropertyMapper {
return @{@"name" : @"n",
@"page" : @"p",
@"desc" : @"ext.desc",
@"bookID" : @[@"id",@"ID",@"book_id"]};
}
model的一个属性为其他模型
不需要其他操作
容器类型
@class Shadow, Border, Attachment;
@interface Attributes
@property NSString *name;
@property NSArray *shadows;
@property NSSet *borders;
@property NSMutableDictionary *attachments;
@end
@implementation Attributes
+ (NSDictionary *)modelContainerPropertyGenericClass {
return @{@"shadows" : [Shadow class],
@"borders" : Border.class,
@"attachments" : @"Attachment" };
}
@end
黑名单与白名单(个人不常用)
@interface User
@property NSString *name;
@property NSUInteger age;
@end
@implementation Attributes
+ (NSArray *)modelPropertyBlacklist {
return @[@"test1", @"test2"];
}
+ (NSArray *)modelPropertyWhitelist {
return @[@"name"];
}
@end
数据校验与自定义转换(灵活使用)
{
"name":"Harry",
"timestamp" : 1445534567
}
@interface User
@property NSString *name;
@property NSDate *createdAt;
@end
@implementation User
- (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic {
NSNumber *timestamp = dic[@"timestamp"];
if (![timestamp isKindOfClass:[NSNumber class]]) return NO;
_createdAt = [NSDate dateWithTimeIntervalSince1970:timestamp.floatValue];
return YES;
}
- (BOOL)modelCustomTransformToDictionary:(NSMutableDictionary *)dic {
if (!_createdAt) return NO;
dic[@"timestamp"] = @(n.timeIntervalSince1970);
return YES;
}
@end
modelCustomTransformFromDictionary:
模型转换完成后会调用,在这里可以做一些值的修改
- (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic {
if ([dic[@"recordStatus"] isKindOfClass:[NSString class]]) {
NSString *invType = dic[@"recordStatus"] ;
if (invType.length == 0 ) {
_recordStatus = @"";
}
NSDictionary *dic = @{@"0":@"未确认",
@"1":@"确认已通过",
@"2":@"确认未通过"
};
_recordStatus = dic[invType];
}
return YES;
}
modelCustomTransformToDictionary:
,当 Model 转为 JSON 完成后,该方法会被调用。可以对不需要的字段进行处理
- (BOOL)modelCustomTransformToDictionary:(NSMutableDictionary *)dic {
if ([dic.allKeys containsObject:@"oilTypeText"]) {
dic[@"oilTypeText"] = nil;
}
return YES;
}