MJExtension源碼解讀與實踐使用(一)

對于一個程序員來說软能,如果使用了第三方框架饰潜,最好是包一層再去操作硝烂,比如使用AFN時箕别,封裝一個網(wǎng)絡工具類(例如:NetworkTool),然后在項目中直接使用這個類進行網(wǎng)絡請求,這樣做的好處的如果以后作者不更新了串稀, 你要換一個網(wǎng)絡框架的話直接在該類中修改即可除抛,就不用跑到每個發(fā)網(wǎng)絡請求的地方進行修改。實際項目中對于Model的解析我一般會在Base中新建一個BaseModel,然后項目中的所有Model都繼承于BaseModel.

目錄:
一:自己寫一個框架自動轉模型思路分析
二母截、 MJExtension框架與KVC的底層實現(xiàn)的區(qū)別
三到忽、為什么要用MJExtension?
四清寇、對MJExtension框架進行封裝
五喘漏、MJExtension能做什么?(結合實際情況進行操作)
1.字典轉模型(最常見)
2.JSON字符串轉模型(很少見)
3.模型中嵌套模型
4.模型中有個數(shù)組屬性华烟,數(shù)組字典里面嵌套數(shù)組字典
5.模型中的屬性名和字典中的key不相同
6.將一個字典數(shù)組轉成模型數(shù)組<<見下篇文章>>
7.將一個模型轉成字典<<見下篇文章>>
8.將一個模型數(shù)組轉成字典數(shù)組<<見下篇文章>>
9.統(tǒng)一轉換屬性名(比如駝峰轉下劃線)<<見下篇文章>>
六翩迈、項目中的實際操作
1.單獨取某個字段
2.字典轉模型
3.JSON字符串轉模型
4.模型中嵌套模型
5.數(shù)組字典,又包含數(shù)組字典

一盔夜、如果要自己寫一個框架自動轉模型,大致思路如下:

1> 遍歷模型中的屬性,然后拿到屬性名作為鍵值去字典中尋找值.
2> 找到值后根據(jù)模型的屬性的類型將值轉成正確的類型
3> 賦值

二负饲、 MJExtension框架與KVC的底層實現(xiàn)的區(qū)別

1> KVC是通過遍歷字典中的所有key,然后去模型中尋找對應的屬性
2> MJ框架是通過先遍歷模型中的屬性,然后去字典中尋找對應的key,所以用MJ框架的時候,模型中的屬性和字典可以不用一一對應,同樣能達到給模型賦值的效果.

三、為什么要用MJExtension喂链?

1.上手快返十,使用簡單。
2.大牛寫的框架椭微,值得認可洞坑,考慮比較謹慎。
3.現(xiàn)在已經(jīng)到了3.0版本赏表,比較穩(wěn)定检诗。
4.如果是自己通過KVC自動映射的話,切必須要保證模型中的屬性名要和字典中的key一一對應,否則使用KVC運行時會報錯的.

四瓢剿、對MJExtension框架進行封裝

.h文件

@interface BaseModel : NSObject
//id
@property(nonatomic,copy)NSString *ID;
//通過字典來創(chuàng)建一個模型
+ (instancetype)objectWithDic:(NSDictionary*)dic;

//通過JSON字符串轉模型
+ (instancetype)objectWithJSONStr:(NSString *)jsonStr;

//通過字典數(shù)組來創(chuàng)建一個模型數(shù)組
+ (NSArray*)objectsWithArray:(NSArray<NSDictionary*>*)arr;
.m文件
+ (NSDictionary *)mj_replacedKeyFromPropertyName{
    return @{@"ID":@"id"};  
}
+ (instancetype)objectWithDic:(NSDictionary*)dic{
    //容錯處理
    if (![dic isKindOfClass:[NSDictionary class]]||!dic) {
        return nil;
    }
    
    NSString *className = [NSString stringWithUTF8String:object_getClassName(self)];    
    return [NSClassFromString(className) mj_objectWithKeyValues:dic];
    
}
+ (instancetype)objectWithJSONStr:(NSString *)jsonStr{
    //容錯處理
    if (![jsonStr isKindOfClass:[NSString class]]||!jsonStr) {   
        return nil;
    }
    NSString *className = [NSString stringWithUTF8String:object_getClassName(self)];
    return [NSClassFromString(className) mj_objectWithKeyValues:jsonStr];
}
+ (NSArray*)objectsWithArray:(NSArray<NSDictionary*>*)arr{
    
    //獲取子類名
    NSString * className =  [NSString stringWithUTF8String:object_getClassName(self)];
    return [NSClassFromString(className) mj_objectArrayWithKeyValuesArray:arr];
    
}

五逢慌、MJExtension能做什么?(結合實際情況進行操作)

1.字典轉模型(最常見)
/***************** UserModel***************/
import "BaseModel.h"
typedef enum {
    SexMale,
    SexFemale
} Sex;
@interface UserModel : BaseModel
@property(nonatomic,copy)NSString *name;
@property (nonatomic,assign) Sex sex;
@property (nonatomic,assign) NSInteger age;
@end
/***********************************************/
    NSDictionary *dic = @{@"id":@"1234",
                          @"name":@"flowerflower",
                          @"age":@20,
                          @"sex": @(SexFemale)
                          };
    
    
    UserModel *model  = [UserModel objectWithDic:dic];
    
    NSLog(@"dic = %@ \n id= %@,name= %@,age:%zd,sex:%zd",dic,model.ID,model.name,model.age,model.sex);
 
image.png
2.JSON字符串轉模型(很少見)
    NSString *jsonStr = @"{\"id\":\"1234\",\"name\":\"flowerflower\", \"age\":20}";
    UserModel *model = [UserModel objectWithJSONStr:jsonStr];
    NSLog(@"jsonStr = %@ \n id= %@,name= %@,age:%zd",jsonStr,model.ID,model.name,model.age);
image.png
3.模型中嵌套模型
/***************** UserModel***************/
#import "BaseModel.h"
#import "DogModel.h"
typedef enum {
    SexMale,
    SexFemale
} Sex;
@interface UserModel : BaseModel

@property(nonatomic,strong)DogModel *dogModel;

@property(nonatomic)NSDictionary  *dog;

@property(nonatomic,copy)NSString *msg;

@property(nonatomic,copy)NSString *name;

@property (nonatomic,assign) Sex sex;

@property (nonatomic,assign) NSInteger age;

@end

/***************** DogModel***************/
#import "BaseModel.h"
@class UserModel;
@interface DogModel : BaseModel
@property(nonatomic,copy)NSString *name;
@property(nonatomic,copy)NSString *height;
@property(nonatomic)UserModel *user;


/***********************************************/
 NSDictionary *dic = @{
                          @"msg":@"成功",
                          @"dog":@{
                                  @"name":@"小花貓",
                                  @"height":@"0.5",
                                  @"user":@{
                                          @"name":@"小小狗",
                                          @"age":@15,
                                          }
                                  },
                          
                          };
    
    UserModel *model = [UserModel objectWithDic:dic];
    DogModel *dogModel = [DogModel objectWithDic:model.dog];
    NSString *msg = model.msg;
    NSString *name = dogModel.name;
    NSString *height = dogModel.height;
    
    NSString *userName = dogModel.user.name;
    NSInteger userAge = dogModel.user.age;
    
    NSLog(@"dic = %@, \n msg=%@, name = %@, height = %@ userName = %@ userAge = %zd",dic,msg,name,height,userName,userAge);
image.png
4.模型中有個數(shù)組屬性间狂,數(shù)組字典里面嵌套數(shù)組字典
圖片.png

對于我們前端來說無非便是【解析數(shù)據(jù)->獲取數(shù)據(jù)->展示數(shù)據(jù)】攻泼。例如上面截圖,下面會在項目中的實際操作貼上代碼鉴象。無非就是多了一層嵌套忙菠,沒有嵌套是怎么做的,那么現(xiàn)在嵌套了一層也是一樣的做法纺弊,無非就是多遍歷一次即可牛欢。具體闡述見下面的示例demo.

5.模型中的屬性名和字典中的key不相同

例如id屬于系統(tǒng)的關鍵字,所有建議寫成大寫的ID淆游,直接

+ (NSDictionary *)mj_replacedKeyFromPropertyName{
    return @{@"ID":@"id"};  
}

這里就不做過多的演示

六傍睹、項目中的實際操作

1.單獨取某個字段
NSString *dayStr= resposeObject[@"data"][@"day"];

后臺返回示例

(lldb) po resposeObject
{
    data =     {
        continueDay = 3;
        day = "27;28";
    };
    msg = "\U83b7\U53d6\U8fde\U7eed\U7b7e\U5230\U5929\U6570";
    result = 0;
    systemTime = 1498637374374;
}

2.字典轉模型
image.png
/***************** JYWalletModel***************/
#import "BaseModel.h"
@interface JYWalletModel : BaseModel
@property(nonatomic,assign)long accountAmount;
@property(nonatomic,copy)NSString *accountNo;
@property(nonatomic,copy)NSString *accountTotal;
/********************字典轉模型***************************/
  JYWalletModel *model  = [JYWalletModel objectWithDic:resposeObject[@"data"]];
3.JSON字符串轉模型

例如調(diào)用支付寶時隔盛,后臺返回


image.png
/***************** JYPayInfoModel***************/

@interface JYPayInfoModel : BaseModel
@property(nonatomic,copy)NSString *payInfo;
@end
/***********************字典轉模型************************/
    JYPayInfoModel *user = [JYPayInfoModel objectWithDic:resposeObject[@"data"]];

最后拿到user.payInfo丟給支付寶即可。

4.模型中有個數(shù)組屬性拾稳,數(shù)組字典里面嵌套數(shù)組字典
圖片.png
再這里將請到的數(shù)據(jù)寫成了plist吮炕,寫了示例demo。
- (NSArray *)groupArr{
    if (!_groupArr) {
      NSDictionary *contentDic = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"content" ofType:@"plist"]];
        
        NSArray *dictArray = contentDic[@"groups"];
        NSMutableArray *temp = [NSMutableArray array];
        
        for (NSDictionary *dic in dictArray) {
            GroupModel *group = [GroupModel objectWithDic:dic];
            NSMutableArray *temp1 = [NSMutableArray array];
            
            for (NSDictionary *dic1 in dic[@"students"]) {
                StudentModel *model = [StudentModel objectWithDic:dic1];
                [temp1 addObject:model];
            }
             group.students = temp1;
            [temp addObject:group];
        }
        _groupArr = temp;
    }
    return _groupArr;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.groupArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    GroupModel * model = self.groupArr[section];
    return model.students.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    GroupModel *model = self.groupArr[indexPath.section];
    StudentModel *studentModel = model.students[indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cellID"];   
    }
    cell.textLabel.text =  studentModel.name;
    cell.detailTextLabel.text = studentModel.department;

    return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UILabel *headerView = [[UILabel alloc]init];
    GroupModel *model = self.groupArr[section];
    headerView.text =model.group_name;
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}
曬個圖圖更美觀
圖片.png
5.數(shù)組字典访得,又包含數(shù)組字典
image.png
image.png

處理方式:

/***************** JYCategorysModel***************/
@interface JYCategorysModel : BaseModel

@property(nonatomic,copy)NSString *name; //商品名稱

@property(nonatomic,copy)NSString *icon; //商品icon

@property (nonatomic, copy) NSString *pid;
//當前是否選定
@property (nonatomic, assign) BOOL isSelected;

@property(nonatomic,copy)NSArray *childrenListArr;

@end
@implementation JYCategorysModel

+ (NSDictionary *)mj_replacedKeyFromPropertyName{
    return@{@"childrenListArr":@"child"
            };
}

/********************轉模型過程步驟***************************/
//控制器類
 self.categorysArr = [JYCategorysModel objectsWithArray:resposeObject[@"data"]];
        self.funView.dataArr = self.categorysArr;

- (JYFunView *)funView{
    
    if (!_funView) {

        _funView = [[JYFunView alloc]initWithFrame:CGRectMake(0, 0, Screen_Width, funHight+bannerHight)];
        JYWeakSelf;
        _funView.isNeedBannerHeader = YES;
        _funView.FunDidSelectItemAtIndexPath = ^(NSArray *leftArr){
      
            weakSelf.leftArr = [JYChildrenListMoel objectsWithArray:leftArr];
            if ([[weakSelf.leftArr firstObject] ID] == nil) {
                [weakSelf.goodsListArr removeAllObjects];
                [weakSelf.tableView reloadData];
            }else{
                [weakSelf.goodsListArr removeAllObjects];
            [weakSelf.viewModel SelectedProducts:[[weakSelf.leftArr firstObject] ID]];
            }
            [weakSelf tableView:weakSelf.leftTableView didSelectRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];  
            [weakSelf.leftTableView reloadData];
        };
    }
    return _funView;
}
JYFunView類
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    for (JYCategorysModel *model in self.dataArr) {
        model.selectedFlag = NO;
    }
    if (self.dataArr.count <= 0) return;
    JYCategorysModel *catgoryModel = self.dataArr[indexPath.row];
    catgoryModel.selectedFlag = YES;
    JYCategorysModel *model = [self.dataArr safeObjectAtIndex:indexPath.row];
    
    if (_FunDidSelectItemAtIndexPath) {
        _FunDidSelectItemAtIndexPath(model.childrenListArr);
    }
    [collectionView reloadData];
 
}
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末龙亲,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子悍抑,更是在濱河造成了極大的恐慌鳄炉,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,744評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件传趾,死亡現(xiàn)場離奇詭異迎膜,居然都是意外死亡,警方通過查閱死者的電腦和手機浆兰,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,505評論 3 392
  • 文/潘曉璐 我一進店門磕仅,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人簸呈,你說我怎么就攤上這事榕订。” “怎么了蜕便?”我有些...
    開封第一講書人閱讀 163,105評論 0 353
  • 文/不壞的土叔 我叫張陵劫恒,是天一觀的道長。 經(jīng)常有香客問我轿腺,道長两嘴,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,242評論 1 292
  • 正文 為了忘掉前任族壳,我火速辦了婚禮憔辫,結果婚禮上,老公的妹妹穿的比我還像新娘仿荆。我一直安慰自己贰您,他們只是感情好,可當我...
    茶點故事閱讀 67,269評論 6 389
  • 文/花漫 我一把揭開白布拢操。 她就那樣靜靜地躺著锦亦,像睡著了一般。 火紅的嫁衣襯著肌膚如雪令境。 梳的紋絲不亂的頭發(fā)上杠园,一...
    開封第一講書人閱讀 51,215評論 1 299
  • 那天,我揣著相機與錄音舔庶,去河邊找鬼抛蚁。 笑死玲昧,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的篮绿。 我是一名探鬼主播,決...
    沈念sama閱讀 40,096評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼吕漂,長吁一口氣:“原來是場噩夢啊……” “哼亲配!你這毒婦竟也來了?” 一聲冷哼從身側響起惶凝,我...
    開封第一講書人閱讀 38,939評論 0 274
  • 序言:老撾萬榮一對情侶失蹤吼虎,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后苍鲜,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體思灰,經(jīng)...
    沈念sama閱讀 45,354評論 1 311
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,573評論 2 333
  • 正文 我和宋清朗相戀三年混滔,在試婚紗的時候發(fā)現(xiàn)自己被綠了洒疚。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,745評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡坯屿,死狀恐怖油湖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情领跛,我是刑警寧澤乏德,帶...
    沈念sama閱讀 35,448評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站吠昭,受9級特大地震影響喊括,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜矢棚,卻給世界環(huán)境...
    茶點故事閱讀 41,048評論 3 327
  • 文/蒙蒙 一郑什、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧幻妓,春花似錦蹦误、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,683評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至妹沙,卻和暖如春偶洋,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背距糖。 一陣腳步聲響...
    開封第一講書人閱讀 32,838評論 1 269
  • 我被黑心中介騙來泰國打工玄窝, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留牵寺,地道東北人。 一個月前我還...
    沈念sama閱讀 47,776評論 2 369
  • 正文 我出身青樓恩脂,卻偏偏與公主長得像帽氓,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子俩块,可洞房花燭夜當晚...
    茶點故事閱讀 44,652評論 2 354

推薦閱讀更多精彩內(nèi)容

  • 在日常的iOS開發(fā)中黎休,總會進行數(shù)據(jù)的轉換,比如請求服務端獲取數(shù)據(jù)玉凯,解析數(shù)據(jù)势腮,轉換成對應的model,這個轉換過...
    繁星mind閱讀 13,944評論 7 49
  • 對于從事 iOS 開發(fā)人員來說漫仆,所有的人都會答出【runtime 是運行時】什么情況下用runtime?大部分人能...
    夢夜繁星閱讀 3,721評論 7 64
  • 方法一
    幾千里也閱讀 601評論 0 0
  • 挺難寫的捎拯,倒不是思路不清晰,文字組不上的問題盲厌。倒是著人多事煩署照,這不剛寫了第一個字 哎 正想好了標點符號往上寫的時候...
    綠樹沙閱讀 336評論 0 0
  • 文/陳慧聰 九月藤树,穿過留在夏季的所有溫暖,在心底留下一絲絲的不舍拓萌,讓記憶在筆尖流逝岁钓。 九月也是鍛煉意志力的熔爐,你...
    c迎風奔跑閱讀 570評論 6 9