- 溫馨提醒:今天使用cocoaPods導(dǎo)入最新版本,使用時(shí)發(fā)現(xiàn)需要在方法名稱前面添加mj_。話說到現(xiàn)在我才使用cocoapods,是有多懶。。。

服務(wù)器數(shù)據(jù)返回結(jié)構(gòu)
模型代碼
// ZZYProjectModel.h
#import <Foundation/Foundation.h>
@class ZZYProjectLeaderModel;
@interface ZZYProjectModel : NSObject
@property (nonatomic, copy) NSString * ID;
@property (nonatomic, copy) NSString * name;
@property (nonatomic, copy) NSString * progress;
@property (nonatomic, strong) NSArray * members;
@property (nonatomic, strong) ZZYProjectLeaderModel * leader;
@end
// ZZYProjectModel.m
#import "ZZYProjectModel.h"
#import "ZZYProjectMemberModel.h"
@implementation ZZYProjectModel
+ (NSDictionary *)objectClassInArray
{
return @{@"members":[ZZYProjectMemberModel class]};
}
+ (NSDictionary *)replacedKeyFromPropertyName
{
return @{@"dec":@"description",
@"ID":@"id"};
}
首先我們分析數(shù)據(jù)的層次結(jié)構(gòu):
- 數(shù)據(jù)最外層是一個(gè)字典,我們需要獲得的是字典中的 projects 數(shù)組數(shù)據(jù)
- projects 數(shù)組是一個(gè)一個(gè)的字典,而這個(gè)字典中又包含字典 leader 和字典數(shù)組 members
字典轉(zhuǎn)換模型分析
- 此處我是將字典 leader 與 字典數(shù)組 members 分別放在了兩個(gè)模型 ZZYProjectLeaderModel 與 ZZYProjectMemberModel中
- 上述兩個(gè)模型統(tǒng)一位于模型 ZZYProjectModel 中
控制器中模型的創(chuàng)建過程
//在數(shù)據(jù)網(wǎng)絡(luò)請求成功之后,獲取到需要的數(shù)據(jù)
NSArray * dictArr = [NSArray arrayWithArray:responseObject[@"data"][@"projects"]];
//調(diào)用MJExtension的方法,將字典數(shù)組轉(zhuǎn)化為模型數(shù)組
NSArray * modelsArr = [ZZYProjectModel objectArrayWithKeyValuesArray:dictArr];
//遍歷模型數(shù)組,將模型數(shù)組的模型數(shù)據(jù)賦值給一個(gè)數(shù)組
NSMutableArray * arr = [NSMutableArray array];
for (ZZYProjectModel * model in modelsArr) {
[arr addObject:model];
}
//此處可以將數(shù)組賦值給dataArr數(shù)據(jù)源數(shù)組,進(jìn)行相應(yīng)的操作
- 以上是我最常用的創(chuàng)建方式
幾點(diǎn)注意
- 創(chuàng)建模型的時(shí)候要保證模型的屬性與返回的數(shù)據(jù)中字典的key值相同
- 當(dāng)服務(wù)器返回的數(shù)據(jù)key值與系統(tǒng)關(guān)鍵字沖突的時(shí)候,最常見的例如:id,我們需要在模型.m文件中使用下述方法替換關(guān)鍵字
+ (NSDictionary *)replacedKeyFromPropertyName
- 字典中包含數(shù)組字典的時(shí)候,想要將數(shù)組字典頁轉(zhuǎn)換為模型,需要在字典對應(yīng)的模型中,聲明數(shù)組字典對應(yīng)key指的數(shù)組;并且在.m文件中使用下述方法聲明該數(shù)組中的成員變量的類型
+ (NSDictionary *)objectClassInArray
- 本人最常用的MJExtension字典轉(zhuǎn)模型的方法
+ (NSMutableArray *)objectArrayWithKeyValuesArray:(NSArray *)keyValuesArray字典數(shù)組轉(zhuǎn)換成模型數(shù)組
+ (instancetype)objectWithKeyValues:(id)keyValues字典轉(zhuǎn)化為模型