笔者之前一直在用MJExtension来做网络数据模型转换,最近发现这个库在某些场景下转换会出现问题,然后就尝试了使用YYModel。YYModel很久之前就听说过,源代码写得很精妙,也有很多开发者在用。这里简单通过demo总结下它的用法。
新建两个model:YYAuthor和YYBook。
YYAuthor.h
//
// YYAuthor.h
// YYModelDemo
//
// Created by mac on 2019/05/01.
// Copyright © 2019 mac All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface YYAuthor : NSObject<NSCopying,NSCoding,NSMutableCopying>
@property (nonatomic,copy) NSString *name;
@property (nonatomic,strong) NSDate *birthDay;
@end
NS_ASSUME_NONNULL_END
YYAuthor.m
//
// YYAuthor.m
// YYModelDemo
//
// Created by mac on 2019/05/01
// Copyright © 2019 mac All rights reserved.
//
#import "YYAuthor.h"
#import <NSObject+YYModel.h>
@implementation YYAuthor
/**
If the key in JSON/Dictionary does not match to the model's property name,
implements this method and returns the additional mapper.
*/
+ (NSDictionary *)modelCustomPropertyMapper
{
return @{@"birthDay":@"birthday"};
}
- (void)encodeWithCoder:(NSCoder *)coder
{
[self yy_modelEncodeWithCoder:coder];
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
return [self yy_modelInitWithCoder:aDecoder];
}
- (id)copyWithZone:(NSZone *)zone
{
return [self yy_modelCopy];
}
- (id)mutableCopyWithZone:(nullable NSZone *)zone
{
YYAuthor *copy;
if ((copy = [[[self class] alloc] init])) {
[copy setValue:self.name forKey:@"name"