開(kāi)篇說(shuō)明:
雖然網(wǎng)上有很多講解YYModel使用方法的文章,包括YYModel作者也在github上對(duì)其做了使用說(shuō)明。
但在我實(shí)際使用過(guò)程中,依然發(fā)現(xiàn)文檔的不完善,比如對(duì)于復(fù)雜的模型(如多層嵌套)講解的仍不透徹,同時(shí)本文也會(huì)介紹一神器配合YYModel使用,讓你感受分分鐘搞定模型創(chuàng)建的酸爽。
當(dāng)然為了減少讀者的學(xué)習(xí)成本,本會(huì)對(duì)YYModel作者的文檔進(jìn)行豐富和擴(kuò)展。
可在github上下載Demo,以便更直觀了解各種使用場(chǎng)景詳細(xì)代碼。
文章只要包含:
- 詳解YYModel的多種使用場(chǎng)景
- 拓展插件,讓你一分鐘搞定所有的模型的創(chuàng)建和調(diào)用。
一、YYModel的使用場(chǎng)景
1.簡(jiǎn)單的 Model 與 JSON 相互轉(zhuǎn)換
// JSON:
{
"uid":123456,
"name":"Harry",
"created":"1965-07-31T00:00:00+0000"
}
// Model:
@interface User : NSObject
@property UInt64 uid;
@property NSString *name;
@property NSDate *created;
@end
@implementation User
@end
// 將 JSON (NSData,NSString,NSDictionary) 轉(zhuǎn)換為 Model:
User *user = [User yy_modelWithJSON:json];
// 將 Model 轉(zhuǎn)換為 JSON 對(duì)象:
NSDictionary *json = [user yy_modelToJSONObject];
JSON/Dictionary 中的對(duì)象類(lèi)型與 Model 屬性不一致時(shí),YYModel 將會(huì)進(jìn)行如下自動(dòng)轉(zhuǎn)換。自動(dòng)轉(zhuǎn)換不支持的值將會(huì)被忽略,以避免各種潛在的崩潰問(wèn)題。

2.Model 屬性名和 JSON 中的 Key 不相同
// JSON:
{
"n":"Harry Pottery",
"p": 256,
"ext" : {
"desc" : "A book written by J.K.Rowing."
},
"ID" : 100010
}
// Model:
@interface Book : NSObject
@property NSString *name;
@property NSInteger page;
@property NSString *desc;
@property NSString *bookID;
@end
@implementation Book
//返回一個(gè) Dict,將 Model 屬性名對(duì)映射到 JSON 的 Key。
+ (NSDictionary *)modelCustomPropertyMapper {
return @{@"name" : @"n",
@"page" : @"p",
@"desc" : @"ext.desc",
@"bookID" : @[@"id",@"ID",@"book_id"]};
}
@end
你可以把一個(gè)或一組 json key (key path) 映射到一個(gè)或多個(gè)屬性。如果一個(gè)屬性沒(méi)有映射關(guān)系,那默認(rèn)會(huì)使用相同屬性名作為映射。
在 json->model 的過(guò)程中:如果一個(gè)屬性對(duì)應(yīng)了多個(gè) json key,那么轉(zhuǎn)換過(guò)程會(huì)按順序查找,并使用第一個(gè)不為空的值。
在 model->json 的過(guò)程中:如果一個(gè)屬性對(duì)應(yīng)了多個(gè) json key (key path),那么轉(zhuǎn)換過(guò)程僅會(huì)處理第一個(gè) json key (key path);如果多個(gè)屬性對(duì)應(yīng)了同一個(gè) json key,則轉(zhuǎn)換過(guò)過(guò)程會(huì)使用其中任意一個(gè)不為空的值。
3.Model 包含其他 Model
// JSON
{
"author":{
"name":"J.K.Rowling",
"birthday":"1965-07-31T00:00:00+0000"
},
"name":"Harry Potter",
"pages":256
}
// Model: 什么都不用做,轉(zhuǎn)換會(huì)自動(dòng)完成
@interface Author : NSObject
@property NSString *name;
@property NSDate *birthday;
@end
@implementation Author
@end
@interface Book : NSObject
@property NSString *name;
@property NSUInteger pages;
@property Author *author; //Book 包含 Author 屬性
@end
@implementation Book
@end
4.容器類(lèi)屬性
@class Shadow, Border, Attachment;
@interface Attributes
@property NSString *name;
@property NSArray *shadows; //Array<Shadow>
@property NSSet *borders; //Set<Border>
@property NSMutableDictionary *attachments; //Dict<NSString,Attachment>
@end
@implementation Attributes
// 返回容器類(lèi)中的所需要存放的數(shù)據(jù)類(lèi)型 (以 Class 或 Class Name 的形式)。
+ (NSDictionary *)modelContainerPropertyGenericClass {
return @{@"shadows" : [Shadow class],
@"borders" : Border.class,
@"attachments" : @"Attachment" };
}
@end
在實(shí)際使用過(guò)過(guò)程中,[Shadow class],Border.class,@"Attachment"沒(méi)有明顯的區(qū)別。
這里僅僅是創(chuàng)建作者有說(shuō)明,實(shí)際使用時(shí),需要對(duì)其遍歷,取出容器中得字典,然后繼續(xù)字典轉(zhuǎn)模型。(YYModel的核心是通過(guò)runtime獲取結(jié)構(gòu)體中得Ivars的值,將此值定義為key,然后給key賦value值,所以我們需要自己遍歷容器(NSArray,NSSet,NSDictionary),獲取每一個(gè)值,通過(guò)objc_msgSend動(dòng)態(tài)調(diào)用對(duì)象的set方法給屬性賦值)。
- 具體的代碼實(shí)現(xiàn)如下:
NSDictionary *json =[self getJsonWithJsonName:@"ContainerModel"];
ContainerModel *containModel = [ContainerModel yy_modelWithDictionary:json];
NSDictionary *dataDict = [containModel valueForKey:@"data"];
//定義數(shù)組,接受key為list的數(shù)組
self.listArray = [dataDict valueForKey:@"list"];
//遍歷數(shù)組
[self.listArray enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSDictionary *listDict = obj;
//獲取數(shù)組中得字典
List *listModel = [List yy_modelWithDictionary:listDict];
//獲取count 和 id
NSString *count = [listModel valueForKey:@"count"];
NSString *id = [listModel valueForKey:@"id"];
5.黑名單與白名單
@interface User
@property NSString *name;
@property NSUInteger age;
@end
@implementation Attributes
// 如果實(shí)現(xiàn)了該方法,則處理過(guò)程中會(huì)忽略該列表內(nèi)的所有屬性
+ (NSArray *)modelPropertyBlacklist {
return @[@"test1", @"test2"];
}
// 如果實(shí)現(xiàn)了該方法,則處理過(guò)程中不會(huì)處理該列表外的屬性。
+ (NSArray *)modelPropertyWhitelist {
return @[@"name"];
}
@end
6.數(shù)據(jù)校驗(yàn)與自定義轉(zhuǎn)換
實(shí)際這個(gè)分類(lèi)的目的比較簡(jiǎn)單和明確。
就是對(duì)判斷是否為時(shí)間戳,然后對(duì)時(shí)間戳進(jìn)行處理,調(diào)用
_createdAt = [NSDate dateWithTimeIntervalSince1970:timestamp.floatValue];
獲取時(shí)間。
// JSON:
{
"name":"Harry",
"timestamp" : 1445534567 //時(shí)間戳
}
// Model:
@interface User
@property NSString *name;
@property NSDate *createdAt;
@end
@implementation User
// 當(dāng) JSON 轉(zhuǎn)為 Model 完成后,該方法會(huì)被調(diào)用。
// 你可以在這里對(duì)數(shù)據(jù)進(jìn)行校驗(yàn),如果校驗(yàn)不通過(guò),可以返回 NO,則該 Model 會(huì)被忽略。
// 你也可以在這里做一些自動(dòng)轉(zhuǎn)換不能完成的工作。
- (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic {
NSNumber *timestamp = dic[@"timestamp"];
if (![timestamp isKindOfClass:[NSNumber class]]) return NO;
_createdAt = [NSDate dateWithTimeIntervalSince1970:timestamp.floatValue];
return YES;
}
// 當(dāng) Model 轉(zhuǎn)為 JSON 完成后,該方法會(huì)被調(diào)用。
// 你可以在這里對(duì)數(shù)據(jù)進(jìn)行校驗(yàn),如果校驗(yàn)不通過(guò),可以返回 NO,則該 Model 會(huì)被忽略。
// 你也可以在這里做一些自動(dòng)轉(zhuǎn)換不能完成的工作。
- (BOOL)modelCustomTransformToDictionary:(NSMutableDictionary *)dic {
if (!_createdAt) return NO;
dic[@"timestamp"] = @(n.timeIntervalSince1970);
return YES;
}
@end
- 需要注意的時(shí),如果用插件,對(duì)時(shí)間戳類(lèi)型或默認(rèn)創(chuàng)建為NSUInteger類(lèi)型,需要將其更改為NSDate類(lèi)型。
7.Coding/Copying/hash/equal/description
以下方法都是YYModel的簡(jiǎn)單封裝,實(shí)際使用過(guò)程和系統(tǒng)方法區(qū)別不大。對(duì)其感興趣的可以點(diǎn)進(jìn)方法內(nèi)部查看。
@interface YYShadow :NSObject <NSCoding, NSCopying>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) CGSize size;
@end
@implementation YYShadow
// 直接添加以下代碼即可自動(dòng)完成
- (void)encodeWithCoder:(NSCoder *)aCoder {
[self yy_modelEncodeWithCoder:aCoder];
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
return [self yy_modelInitWithCoder:aDecoder];
}
- (id)copyWithZone:(NSZone *)zone {
return [self yy_modelCopy];
}
- (NSUInteger)hash {
return [self yy_modelHash];
}
- (BOOL)isEqual:(id)object {
return [self yy_modelIsEqual:object];
}
- (NSString *)description {
return [self yy_modelDescription];
}
@end
二、ESJsonFormat與YYModel的結(jié)合使用
彩蛋
給大家介紹一款插件,配合ESJsonFormat
配圖:

使用方法:
快捷鍵:shift + control + J
插件安裝方法比較簡(jiǎn)單,在此不贅述,不知道可自行g(shù)oogle。
好處:
- 可以直接將json數(shù)據(jù)復(fù)制,ESJsonFormat會(huì)根據(jù)數(shù)據(jù)類(lèi)型自動(dòng)生成屬性。(建議還是要自行檢查,比如時(shí)間戳,系統(tǒng)會(huì)默認(rèn)幫你生成為NSUInteger,而我們想要的為NSDate類(lèi)型)
- 對(duì)于多模型嵌套,不必創(chuàng)建多個(gè)文件,ESJsonFormat會(huì)自動(dòng)在一個(gè)文件下創(chuàng)建多重類(lèi)型,極其便捷。
至此YYModel的使用已講解完畢,關(guān)于YYModel的底層核心是運(yùn)用runtime獲取類(lèi)結(jié)構(gòu)體中Ivars,進(jìn)行KVC操作,然后根據(jù)不同情況進(jìn)行分別處理。
此處只是傳遞給大家一個(gè)概念,不展開(kāi)講解,網(wǎng)上有很多源碼分析文章,可自學(xué)google學(xué)習(xí)。
文末,做個(gè)綜述。
建議大家有時(shí)間一定要多看底層,分析源碼。不要只會(huì)用,知其然不知其所以然。
如有錯(cuò)誤歡迎指出。
寫(xiě)在最后
我得寫(xiě)作原則:
在技術(shù)學(xué)習(xí)道路上,閱讀量和代碼量絕不能線性提升你的技術(shù)水平。
同樣寫(xiě)文章也是如此,作者所寫(xiě)的文章完全是基于自己對(duì)技術(shù)的理解,在寫(xiě)作時(shí)也力求形象不抽象。絕不copy充數(shù),所以也歡迎大家關(guān)注和參與討論。
技術(shù)學(xué)習(xí)絕不能孤膽英雄獨(dú)闖天涯,而應(yīng)在一群人的交流碰撞,享受智慧火花的狂歡。
希望我的文章能成為你的盛宴,也渴望你的建議能成為我的大餐。
如有錯(cuò)誤請(qǐng)留言指正,對(duì)文章感興趣可以關(guān)注作者不定期更新。