MJExtension是一套“字典和模型之間互相轉換”的輕量級框架
GitHub地址:https://github.com/CoderMJLee/MJExtension
MJExtension能完成的功能
字典 –> 模型 模型 –> 字典 字典數組 –> 模型數組模型數組 –> 字典數組
具體用法主要參考 “NSObject+MJKeyValue.h”
//
// MJUser.h
// 字典與模型的互轉
// 用戶模型
//
#import
typedef enum {
SexMale,
SexFemale
} Sex;
@interface MJUser : NSObject
/** 名稱 */
@property (copy, nonatomic) NSString *name;
/** 頭像 */
@property (copy, nonatomic) NSString *icon;
/** 年齡 */
@property (assign, nonatomic) unsigned int age;
/** 身高 */
@property (strong, nonatomic) NSNumber *height;
/** 財富 */
@property (strong, nonatomic) NSDecimalNumber *money;
/** 性別 */
@property (assign, nonatomic) Sex sex;
/** 同性戀 */
@property (assign, nonatomic, getter=isGay) BOOL gay;
@end
/**
* 簡單的字典 -> 模型
*/
void keyValues2object()
{
// 1.定義一個字典
NSDictionary *dict = @{
@"name" : @"Jack",
@"icon" : @"lufy.png",
@"age" : @"20",
@"height" : @1.55,
@"money" : @"100.9",
@"sex" : @(SexFemale),
@"gay" : @"1"
// @"gay" : @"NO"
// @"gay" : @"true"
};
// 2.將字典轉為MJUser模型
MJUser *user = [MJUser mj_objectWithKeyValues:dict];
// 3.打印MJUser模型的屬性
MJExtensionLog(@"name=%@, icon=%@, age=%zd, height=%@, money=%@, sex=%d, gay=%d", user.name, user.icon, user.age, user.height, user.money, user.sex, user.gay);
}
/**
* JSON字符串 -> 模型
*/
void keyValues2object1()
{
// 1.定義一個JSON字符串
NSString *jsonString = @"{\"name\":\"Jack\", \"icon\":\"lufy.png\", \"age\":20, \"height\":333333.7}";
// 2.將JSON字符串轉為MJUser模型
MJUser *user = [MJUser mj_objectWithKeyValues:jsonString];
// 3.打印MJUser模型的屬性
MJExtensionLog(@"name=%@, icon=%@, age=%d, height=%@", user.name, user.icon, user.age, user.height);
}
//
// MJStatus.h
// 字典與模型的互轉
// 微博模型
//
#import
@class MJUser;
@interface MJStatus : NSObject
/** 微博文本內容 */
@property (copy, nonatomic) NSString *text;
/** 微博作者 */
@property (strong, nonatomic) MJUser *user;
/** 轉發的微博 */
@property (strong, nonatomic) MJStatus *retweetedStatus;
@end
/**
* 復雜的字典 -> 模型 (模型裡面包含了模型)
*/
void keyValues2object2()
{
// 1.定義一個字典
NSDictionary *dict = @{
@"text" : @"是啊,今天天氣確實不錯!",
@"user" : @{
@"name" : @"Jack",
@"icon" : @"lufy.png"
},
@"retweetedStatus" : @{
@"text" : @"今天天氣真不錯!",
@"user" : @{
@"name" : @"Rose",
@"icon" : @"nami.png"
}
}
};
// 2.將字典轉為Status模型
MJStatus *status = [MJStatus mj_objectWithKeyValues:dict];
// 3.打印status的屬性
NSString *text = status.text;
NSString *name = status.user.name;
NSString *icon = status.user.icon;
MJExtensionLog(@"text=%@, name=%@, icon=%@", text, name, icon);
// 4.打印status.retweetedStatus的屬性
NSString *text2 = status.retweetedStatus.text;
NSString *name2 = status.retweetedStatus.user.name;
NSString *icon2 = status.retweetedStatus.user.icon;
MJExtensionLog(@"text2=%@, name2=%@, icon2=%@", text2, name2, icon2);
}
//
// MJStatusResult.h
// 字典與模型的互轉
// 微博結果(用來表示大批量的微博數據)
//
#import "MJBaseObject.h"
@interface MJStatusResult : MJBaseObject
/** 存放著某一頁微博數據(裡面都是Status模型) */
@property (strong, nonatomic) NSMutableArray *statuses;
/** 存放著一堆的廣告數據(裡面都是MJAd模型) */
@property (strong, nonatomic) NSArray *ads;
/** 總數 */
@property (strong, nonatomic) NSNumber *totalNumber;
/** 上一頁的游標 */
@property (assign, nonatomic) long long previousCursor;
/** 下一頁的游標 */
@property (assign, nonatomic) long long nextCursor;
@end
//
// MJStatusResult.m
// 字典與模型的互轉
//
#import "MJStatusResult.h"
@implementation MJStatusResult
+ (NSDictionary *)mj_objectClassInArray
{
return @{
@"statuses" : @"MJStatus",
@"ads" : @"MJAd"
};
}
@end
/**
* 復雜的字典 -> 模型 (模型的數組屬性裡面又裝著模型)
*/
void keyValues2object3()
{
// 1.定義一個字典
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",
@"previousCursor" : @"13476589",
@"nextCursor" : @"13476599"
};
// 2.將字典轉為MJStatusResult模型
MJStatusResult *result = [MJStatusResult mj_objectWithKeyValues:dict];
// 3.打印MJStatusResult模型的簡單屬性
MJExtensionLog(@"totalNumber=%@, previousCursor=%lld, nextCursor=%lld", result.totalNumber, result.previousCursor, result.nextCursor);
// 4.打印statuses數組中的模型屬性
for (MJStatus *status in result.statuses) {
NSString *text = status.text;
NSString *name = status.user.name;
NSString *icon = status.user.icon;
MJExtensionLog(@"text=%@, name=%@, icon=%@", text, name, icon);
}
// 5.打印ads數組中的模型屬性
for (MJAd *ad in result.ads) {
MJExtensionLog(@"image=%@, url=%@", ad.image, ad.url);
}
}
//
// MJStudent.h
// MJExtensionExample
//
#import
@class MJBag;
@interface MJStudent : NSObject
@property (copy, nonatomic) NSString *ID;
@property (copy, nonatomic) NSString *otherName;
@property (copy, nonatomic) NSString *nowName;
@property (copy, nonatomic) NSString *oldName;
@property (copy, nonatomic) NSString *nameChangedTime;
@property (copy, nonatomic) NSString *desc;
@property (strong, nonatomic) MJBag *bag;
@property (strong, nonatomic) NSArray *books;
@end
/**
* 簡單的字典 -> 模型(key替換,比如ID和id。多級映射,比如 oldName 和 name.oldName)
*/
void keyValues2object4()
{
// 1.定義一個字典
NSDictionary *dict = @{
@"id" : @"20",
@"desciption" : @"好孩子",
@"name" : @{
@"newName" : @"lufy",
@"oldName" : @"kitty",
@"info" : @[
@"test-data",
@{@"nameChangedTime" : @"2013-08-07"}
]
},
@"other" : @{
@"bag" : @{
@"name" : @"小書包",
@"price" : @100.7
}
}
};
// 2.將字典轉為MJStudent模型
MJStudent *stu = [MJStudent mj_objectWithKeyValues:dict];
// 3.打印MJStudent模型的屬性
MJExtensionLog(@"ID=%@, desc=%@, otherName=%@, oldName=%@, nowName=%@, nameChangedTime=%@", stu.ID, stu.desc, stu.otherName, stu.oldName, stu.nowName, stu.nameChangedTime);
MJExtensionLog(@"bagName=%@, bagPrice=%f", stu.bag.name, stu.bag.price);
// CFTimeInterval begin = CFAbsoluteTimeGetCurrent();
// for (int i = 0; i< 10000; i++) {
// [MJStudent mj_objectWithKeyValues:dict];
// }
// CFTimeInterval end = CFAbsoluteTimeGetCurrent();
// MJExtensionLog(@"%f", end - begin);
}
//
// MJUser.h
// 字典與模型的互轉
// 用戶模型
#import
typedef enum {
SexMale,
SexFemale
} Sex;
@interface MJUser : NSObject
/** 名稱 */
@property (copy, nonatomic) NSString *name;
/** 頭像 */
@property (copy, nonatomic) NSString *icon;
/** 年齡 */
@property (assign, nonatomic) unsigned int age;
/** 身高 */
@property (strong, nonatomic) NSNumber *height;
/** 財富 */
@property (strong, nonatomic) NSDecimalNumber *money;
/** 性別 */
@property (assign, nonatomic) Sex sex;
/** 同性戀 */
@property (assign, nonatomic, getter=isGay) BOOL gay;
@end
/**
* 字典數組 -> 模型數組
*/
void keyValuesArray2objectArray()
{
// 1.定義一個字典數組
NSArray *dictArray = @[
@{
@"name" : @"Jack",
@"icon" : @"lufy.png",
},
@{
@"name" : @"Rose",
@"icon" : @"nami.png",
}
];
// 2.將字典數組轉為MJUser模型數組
NSArray *userArray = [MJUser mj_objectArrayWithKeyValuesArray:dictArray];
// 3.打印userArray數組中的MJUser模型屬性
for (MJUser *user in userArray) {
MJExtensionLog(@"name=%@, icon=%@", user.name, user.icon);
}
}
/**
* 模型 -> 字典
*/
void object2keyValues()
{
// 1.新建模型
MJUser *user = [[MJUser alloc] init];
user.name = @"Jack";
user.icon = @"lufy.png";
MJStatus *status = [[MJStatus alloc] init];
status.user = user;
status.text = @"今天的心情不錯!";
// 2.將模型轉為字典
NSDictionary *statusDict = status.mj_keyValues;
MJExtensionLog(@"%@", statusDict);
MJExtensionLog(@"%@", [status mj_keyValuesWithKeys:@[@"text"]]);
// 3.新建多級映射的模型
MJStudent *stu = [[MJStudent alloc] init];
stu.ID = @"123";
stu.oldName = @"rose";
stu.nowName = @"jack";
stu.desc = @"handsome";
stu.nameChangedTime = @"2018-09-08";
stu.books = @[@"Good book", @"Red book"];
MJBag *bag = [[MJBag alloc] init];
bag.name = @"小書包";
bag.price = 205;
stu.bag = bag;
NSDictionary *stuDict = stu.mj_keyValues;
MJExtensionLog(@"%@", stuDict);
MJExtensionLog(@"%@", [stu mj_keyValuesWithIgnoredKeys:@[@"bag", @"oldName", @"nowName"]]);
MJExtensionLog(@"%@", stu.mj_JSONString);
[MJStudent mj_referenceReplacedKeyWhenCreatingKeyValues:NO];
MJExtensionLog(@"\n模型轉字典時,字典的key參考replacedKeyFromPropertyName等方法:\n%@", stu.mj_keyValues);
}
/**
* 模型數組 -> 字典數組
*/
void objectArray2keyValuesArray()
{
// 1.新建模型數組
MJUser *user1 = [[MJUser alloc] init];
user1.name = @"Jack";
user1.icon = @"lufy.png";
MJUser *user2 = [[MJUser alloc] init];
user2.name = @"Rose";
user2.icon = @"nami.png";
NSArray *userArray = @[user1, user2];
// 2.將模型數組轉為字典數組
NSArray *dictArray = [MJUser mj_keyValuesArrayWithObjectArray:userArray];
MJExtensionLog(@"%@", dictArray);
}
/**
* CoreData示例
*/
void coreData()
{
NSDictionary *dict = @{
@"name" : @"Jack",
@"icon" : @"lufy.png",
@"age" : @20,
@"height" : @1.55,
@"money" : @"100.9",
@"sex" : @(SexFemale),
@"gay" : @"true"
};
// 這個Demo僅僅提供思路,具體的方法參數需要自己創建
NSManagedObjectContext *context = nil;
MJUser *user = [MJUser mj_objectWithKeyValues:dict context:context];
// 利用CoreData保存模型
[context save:nil];
MJExtensionLog(@"name=%@, icon=%@, age=%zd, height=%f, money=%@, sex=%d, gay=%d", user.name, user.icon, user.age, user.height, user.money, user.sex, user.gay);
}
//
// MJBag.h
// MJExtensionExample
//
#import
@interface MJBag : NSObject
@property (copy, nonatomic) NSString *name;
@property (assign, nonatomic) double price;
@end
//
// MJBag.m
// MJExtensionExample
//
#import "MJBag.h"
#import "MJExtension.h"
@implementation MJBag
// NSCoding實現
MJExtensionCodingImplementation
//+ (NSArray *)mj_ignoredCodingPropertyNames
//{
// return @[@"name"];
//}
@end
/**
* NSCoding示例
*/
void coding()
{
// 創建模型
MJBag *bag = [[MJBag alloc] init];
bag.name = @"Red bag";
bag.price = 200.8;
NSString *file = [NSTemporaryDirectory() stringByAppendingPathComponent:@"bag.data"];
// 歸檔
[NSKeyedArchiver archiveRootObject:bag toFile:file];
// 解檔
MJBag *decodedBag = [NSKeyedUnarchiver unarchiveObjectWithFile:file];
MJExtensionLog(@"name=%@, price=%f", decodedBag.name, decodedBag.price);
}
//
// MJDog.h
// MJExtensionExample
//
#import
@interface MJDog : NSObject
@property (copy, nonatomic) NSString *nickName;
@property (assign, nonatomic) double salePrice;
@property (assign, nonatomic) double runSpeed;
@end
/**
* 統一轉換屬性名(比如駝峰轉下劃線)
*/
void replacedKeyFromPropertyName121()
{
// 1.定義一個字典
NSDictionary *dict = @{
@"nick_name" : @"旺財",
@"sale_price" : @"10.5",
@"run_speed" : @"100.9"
};
// 2.將字典轉為MJUser模型
MJDog *dog = [MJDog mj_objectWithKeyValues:dict];
// 3.打印MJUser模型的屬性
MJExtensionLog(@"nickName=%@, scalePrice=%f runSpeed=%f", dog.nickName, dog.salePrice, dog.runSpeed);
}
//
// Book.h
// MJExtensionExample
//
#import
@class MJBox;
@interface MJBook : NSObject
@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) NSString *publisher;
@property (strong, nonatomic) NSDate *publishedTime;
@property (strong, nonatomic) MJBox *box;
@end
/**
* 過濾字典的值(比如字符串日期處理為NSDate、字符串nil處理為@"")
*/
void newValueFromOldValue()
{
// 1.定義一個字典
NSDictionary *dict = @{
@"name" : @"5分鐘突破iOS開發",
@"publishedTime" : @"2011-09-10"
};
// 2.將字典轉為MJUser模型
MJBook *book = [MJBook mj_objectWithKeyValues:dict];
// 3.打印MJUser模型的屬性
MJExtensionLog(@"name=%@, publisher=%@, publishedTime=%@", book.name, book.publisher, book.publishedTime);
}