字典 --> CoreData
NSDictionary *dict = @{
@"name" : @"Jack",
@"icon" : @"lufy.png",
@"age" : @20,
@"height" : @1.55,
@"money" : @"100.9",
@"sex" : @(SexFemale),
@"gay" : @"true"
};
//字典转为CoreData模型
NSManagedObjectContext *context = nil;
User *user = [User mj_objectWithKeyValues:dict
context:context];
[context save:nil];
归档与解档NSCoding
@interface Bag : NSObject <NSCoding>
@property (copy, nonatomic) NSString *name;
@property (assign, nonatomic) double price;
@end
#import "MJExtension.h"
@implementation Bag
//添加了下面的宏定义
MJExtensionCodingImplementation
/* 实现下面的方法,说明哪些属性不需要归档和解档 */
+ (NSArray *)mj_ignoredCodingPropertyNames{
return @[@"name"];
}
@end
使用实例
//创建模型
Bag *bag = [[Bag alloc] init];
bag.name = @"Red bag";
bag.price = 200.8;
//获取归档路径
NSString *file = [NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/bag.data"];
//归档
[NSKeyedArchiver archiveRootObject:bag toFile:file];
//解档
Bag *decodedBag = [NSKeyedUnarchiver unarchiveObjectWithFile:file];
NSLog(@"name=%@, price=%f", decodedBag.name, decodedBag.price);
// name=(null), price=200.800000