常用的几个方法
json转模型
+ (instancetype)yy_modelWithJSON:(id)json;
模型转字符串
- (NSString *)yy_modelToJSONString
字典转模型
+ (instancetype)yy_modelWithDictionary:(NSDictionary *)dictionary ;
声明数组、字典或者集合里的元素类型时要重写
+ (nullable NSDictionary<NSString *, id> *)modelContainerPropertyGenericClass;
例子:
# YYAlbum.h
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) NSArray *photos; # Array<YYPhoto>
@property (nonatomic, strong) NSDictionary *likedUsers; # Key:name(NSString) Value:user(YYUser)
@property (nonatomic, strong) NSSet *likedUserIds; # Set<NSNumber>
# YYPhoto.h
@property (nonatomic, copy) NSString *url;
@property (nonatomic, copy) NSString *desc;
# YYAlbum.m
#把数组里面带有对象的类型专门按照这个方法,这个格式写出来
-(nullable NSDictionary<NSString *, id> *)modelContainerPropertyGenericClass{
return @{
@"photos" : YYPhoto.class,
@"likedUsers" : YYUser.class,
@"likedUserIds" : NSNumber.class
};
}
字典里的key值与模型的属性值不一致要重置
+ (nullable NSDictionary<NSString *, id> *)modelCustomPropertyMapper;
事例:
# YYMessage.h
@property (nonatomic, assign) uint64_t messageId;
@property (nonatomic, strong) NSString *content;
@property (nonatomic, strong) NSDate *time;
# YYMessage.m
/*!
* 1.该方法是 `字典里的属性Key` 和 `要转化为模型里的属性名` 不一样 而重写的
* 前:模型的属性 后:字典里的属性
*/
+ (nullable NSDictionary<NSString *, id> *)modelCustomPropertyMapper{
return @{@"messageId":@"i",
@"content":@"c",
@"time":@"t"};
}
/*!
* 2. 下面的两个方法 `字典里值`与`模型的值`类型不一样`需要转换`而重写的方法
* NSDate *time dic[@"t"]是double类型的的秒数
*/
/// Dic -> model
- (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic {
self.time = (NSDate *)[NSDate dateWithTimeIntervalSince1970:[dic[@"t"] doubleValue]/1000];
return YES;
}
/// model -> Dic
- (BOOL)modelCustomTransformToDictionary:(NSMutableDictionary *)dic {
dic[@"t"] = @([self.time timeIntervalSince1970] * 1000).description;
return YES;
}
下面两者是属性值在两个dic与模型之间的转化方法
- (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic ;
- (BOOL)modelCustomTransformToDictionary:(NSMutableDictionary *)dic;