MJExtension使用指導(轉)

MJExtension能做什麼?

  1. MJExtension是一套字典和模型之間互相轉換的超輕量級框架

  2. MJExtension能完成的功能

     字典(JSON) --> 模型(Model)
     模型(Model) --> 字典(JSON)
     字典數組(JSON Array) --> 模型數組(Model Array)
     模型數組(Model Array) --> 字典數組(JSON Array

詳盡用法主要參考 main.m中的各個函數 以及 NSObject+MJKeyValue.h

MJExtension和JSONModel、Mantle等框架的區別

1. 轉換速率:

最近一次測試表明:MJExtension > JSONModel > Mantle

各位開發者也可以自行測試

2.具體用法:

JSONModel

要求所有模型類必須繼承自JSONModel基類

Mantle

要求所有模型類必須繼承自MTModel基類

MJExtension

不需要你的模型類繼承任何特殊基類,毫無污染,毫無侵入性

如何使用MJExtension

方法一:cocoapods導入pod 'MJExtension'

方法二:手動導入

將MJExtensionExample/MJExtensionExample/MJExtension文件夾中的所有源代碼拽入項目中
導入主頭文件:#import "MJExtension.h"
MJExtension.h
MJConst.h               
MJConst.m
MJFoundation.h               
MJFoundation.m
MJIvar.h               
MJIvar.m
MJType.h                
MJType.m
NSObject+MJCoding.h     
NSObject+MJCoding.m
NSObject+MJIvar.h       
NSObject+MJIvar.m
NSObject+MJKeyValue.h   
NSObject+MJKeyValue.m

1.最簡單的字典轉模型

typedef enum {
    SexMale,    
    SexFemale} Sex;
@interface User : NSObject
@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) NSString *icon;
@property (assign, nonatomic) int age;
@property (assign, nonatomic) double height;
@property (strong, nonatomic) NSNumber *money;
@property (assign, nonatomic) Sex sex;
@end

NSDictionary *dict = @{
                        @"name" : @"Jack",                 
                        @"icon" : @"lufy.png",               
                        @"age" : @20,               
                        @"height" : @"1.55",               
                        @"money" : @100.9,               
                        @"sex" : @(SexFemale)            
};

// 將字典轉爲User模型
User *user = [User objectWithKeyValues:dict];
NSLog(@"name=%@, icon=%@, age=%d, height=%@, money=%@, sex=%d", user.name, user.icon, user.age, user.height, user.money, user.sex);
// name=Jack, icon=lufy.png, age=20, height=1.550000, money=100.9, sex=1

核心代碼1:

[User objectWithKeyValues:dict]

2.模型中嵌套模型

@interface Status : NSObject
/** 微博文本內容 */
@property (copy, nonatomic) NSString *text;
/** 微博作者 */
@property (strong, nonatomic) User *user;
/** 轉發的微博 */
@property (strong, nonatomic) Status *retweetedStatus;
@end

NSDictionary *dict = @{               
@"text" : @"是啊,今天天氣確實不錯!", 
@"user" : @{                   
             @"name" : @"Jack",                   
             @"icon" : @"lufy.png"                
           },               
@"retweetedStatus" : @{                   
                        @"text" : @"今天天氣真不錯!",                   
                        @"user" : @{                       
                                    @"name" : @"Rose",                       
                                    @"icon" : @"nami.png"                    
                                   }                
                       }            
};

// 將字典轉爲Status模型
Status *status = [Status objectWithKeyValues:dict];
NSString *text = status.text;
NSString *name = status.user.name;
NSString *icon = status.user.icon;
NSLog(@"text=%@, name=%@, icon=%@", text, name, icon);
// text=是啊,今天天氣確實不錯!, name=Jack, icon=lufy.png

NSString *text2 = status.retweetedStatus.text;
NSString *name2 = status.retweetedStatus.user.name;
NSString *icon2 = status.retweetedStatus.user.icon;
NSLog(@"text2=%@, name2=%@, icon2=%@", text2, name2, icon2);
// text2=今天天氣真不錯!, name2=Rose, icon2=nami.png

核心代碼2

[Status objectWithKeyValues:dict]

3.模型中有個數組屬性,數組裏面又要裝着其它模型

@interface Ad : NSObject
@property (copy, nonatomic) NSString *image;
@property (copy, nonatomic) NSString *url;
@end

@interface StatusResult : NSObject
/** 存放着一堆的微博數據(裏面都是Status模型) */
@property (strong, nonatomic) NSMutableArray *statuses;
/** 存放着一堆的廣告數據(裏面都是Ad模型) */
@property (strong, nonatomic) NSArray *ads;
@property (strong, nonatomic) NSNumber *totalNumber;
@end

@implementation StatusResult
// 實現這個方法的目的:告訴MJExtension框架statuses和ads數組裏面裝的是什麼模型
/*    + (NSDictionary *)objectClassInArray{    
return @{         
@"statuses" : [Status class],         
@"ads" : [Ad class]    };
}
+ (Class)objectClassInArray:(NSString *)propertyName{    
if ([propertyName isEqualToString:@"statuses"]) {        
return [Status class];    
} else if ([propertyName isEqualToString:@"ads"]) {        
return [Ad class];    }    
return nil;}
*/

// 這個方法對比上面的2個方法更加沒有侵入性和污染,因爲不需要導入Status和Ad的頭文件
+ (NSDictionary *)objectClassInArray{    
    return @{         
              @"statuses" : @"Status",         
              @"ads" : @"Ad"    
            };
}
@end

NSDictionary *dict = @{                       
@"statuses" : @[                           
                @{                                   
                   @"text" : @"今天天氣真不錯!",
                   @"user" : @{                                   
                                @"name" : @"Rose",
                                @"icon" : @"nami.png"                                                                                  
                              }                            
                 }, 
                                           
                 @{                               
                    @"text" : @"明天去旅遊了", 
                    @"user" : @{                                                                   
                                 @"name" : @"Jack",                                       
                                 @"icon" : @"lufy.png"                               
                               }  
                   } 
                                                                         
                ],                       
 @"ads" :@[                           
           @{                               
              @"image" : @"ad01.png", 
              @"url" : @"http://www.ad01.com"                                                          
            }, 
                                      
           @{                               
              @"image" : @"ad02.png",                                   
              @"url" : @"http://www.ad02.com"                           
            }                       
          ],                       
 @"totalNumber" : @"2014"                    
};
         
         // 將字典轉爲StatusResult模型
         StatusResult *result = [StatusResult objectWithKeyValues:dict];
         NSLog(@"totalNumber=%@", result.totalNumber);
         // totalNumber=2014
         
         // 打印statuses數組中的模型屬性
         for (Status *status in result.statuses) {    
                NSString *text = status.text;    
                NSString *name = status.user.name;    NSString *icon = status.user.icon;    
                NSLog(@"text=%@, name=%@, icon=%@", text, name, icon);}
               // text=今天天氣真不錯!, name=Rose, icon=nami.png
               // text=明天去旅遊了, name=Jack, icon=lufy.png
         
         // 打印ads數組中的模型屬性
         for (Ad *ad in result.ads) {    
                 NSLog(@"image=%@, url=%@", ad.image, ad.url);}
                 // image=ad01.png, url=http://www.ad01.com
                 // image=ad02.png, url=http://www.ad02.com

核心代碼3:

在模型內部實現+ (NSDictionary *)objectClassInArray方法

[StatusResult objectWithKeyValues:dict]

4.模型中的屬性名和字典中的key不相同(或者需要多級映射)

@interface Bag : NSObject
@property (copy, nonatomic) NSString *name;
@property (assign, nonatomic) double price;@end@interface Student : NSObject
@property (copy, nonatomic) NSString *ID;
@property (copy, nonatomic) NSString *desc;
@property (copy, nonatomic) NSString *nowName;
@property (copy, nonatomic) NSString *oldName;
@property (copy, nonatomic) NSString *nameChangedTime;
@property (strong, nonatomic) Bag *bag;
@end

@implementation Student
// 實現這個方法的目的:告訴MJExtension框架模型中的屬性名對應着字典的哪個key
+ (NSDictionary *)replacedKeyFromPropertyName{    
     return @{                
               @"ID" : @"id",                
               @"desc" : @"desciption",                
               @"oldName" : @"name.oldName", 
               @"nowName" : @"name.newName",  
               @"nameChangedTime" : @"name.info.nameChangedTime",                                       
               @"bag" : @"other.bag"            
              };
}

@end

NSDictionary *dict = @{                       
                        @"id" : @"20",                       
                        @"desciption" : @"孩子",
                        @"name" : @{                                                         
                                     @"newName" : @"lufy", 
                                     @"oldName" : @"kitty",  
                                     @"info" : @{                                                                                                   
                                                  @"nameChangedTime" : @"2013-08"                            
                                                 }                       
                                    },                       
                        @"other" : @{                            
                                      @"bag" : @{                                
                                                  @"name" : @"小書包", 
                                                  @"price" : @100.7                                                              
                                                 }                       
                                     }                   
};

// 將字典轉爲Student模型
Student *stu = [Student objectWithKeyValues:dict];
// 打印Student模型的屬性
NSLog(@"ID=%@, desc=%@, oldName=%@, nowName=%@, nameChangedTime=%@", stu.ID, stu.desc, stu.oldName, stu.nowName, stu.nameChangedTime);
// ID=20, desc=孩子, oldName=kitty, nowName=lufy, nameChangedTime=2013-08
NSLog(@"bagName=%@, bagPrice=%f", stu.bag.name, stu.bag.price);
// bagName=小書包, bagPrice=100.700000

核心代碼4:

在模型內部實現+ (NSDictionary *)replacedKeyFromPropertyName方法

[Student objectWithKeyValues:dict]

5.將一個字典數組轉成模型數組

NSArray *dictArray = @[                       
                        @{                           
                           @"name" : @"Jack",                           
                           @"icon" : @"lufy.png",                        
                         },                       
                        @{                           
                           @"name" : @"Rose",                           
                           @"icon" : @"nami.png",                        
                         }                    
                       ];

// 將字典數組轉爲User模型數組
NSArray *userArray = [User objectArrayWithKeyValuesArray:dictArray];
// 打印userArray數組中的User模型屬性
for (User *user in userArray) {   
      NSLog(@"name=%@, icon=%@", user.name, user.icon);}
      // name=Jack, icon=lufy.png
      // name=Rose, icon=nami.png

核心代碼5:

[User objectArrayWithKeyValuesArray:dictArray]

6.將一個模型轉成字典

// 新建模型
  User *user = [[User alloc] init];
user.name = @"Jack";
user.icon = @"lufy.png";

Status *status = [[Status alloc] init];
status.user = user;
status.text = @"今天的心情不錯!";


// 將模型轉爲字典
NSDictionary *statusDict = status.keyValues;
NSLog(@"%@", statusDict);
/*{ text = "今天的心情不錯!";    
    user = {        
             icon = "lufy.png";        
             name = Jack;    
           };
  }*/
  
// 多級映射的模型
Student *stu = [[Student alloc] init];
stu.ID = @"123";
stu.oldName = @"rose";
stu.nowName = @"jack";
stu.desc = @"handsome";
stu.nameChangedTime = @"2018-09-08";

Bag *bag = [[Bag alloc] init];
bag.name = @"小書包";
bag.price = 205;
stu.bag = bag;
NSDictionary *stuDict = stu.keyValues;NSLog(@"%@", stuDict);
/*
{    desciption = handsome;    
       id = 123;    
       name = {        
                info ={            
                nameChangedTime = "2018-09-08";        
                       };        
                newName = jack;        
                oldName = rose;    
               };    
                other = {  
                          bag ={            
                                 name = "小書包";            
                                 price = 205;        
                               };    
                        }; 
               }
 */

核心代碼6:

status.keyValuesstu.keyValues

7.將一個模型數組轉成字典數組

// 新建模型數組
  User *user1 = [[User alloc] init];
user1.name = @"Jack";
user1.icon = @"lufy.png";

User *user2 = [[User alloc] init];
user2.name = @"Rose";
user2.icon = @"nami.png";

NSArray *userArray = @[user1, user2];
// 將模型數組轉爲字典數組
NSArray *dictArray = [User keyValuesArrayWithObjectArray:userArray];
NSLog(@"%@", dictArray);
/*(    
{        icon = "lufy.png";        name = Jack;    },    
{        icon = "nami.png";        name = Rose;    }  )*/

核心代碼7:

[User keyValuesArrayWithObjectArray:userArray]

更多用法

參考NSObject+MJKeyValue.h
參考NSObject+MJCoding.h


作者:PPAbner
鏈接:https://www.jianshu.com/p/93c242452b9b
來源:簡書
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章