归档这种存储方式,比较轻量和高效的. 之前不怎么使用,现在用起来了,几个笔记也好! 以下是随手写的一个示例Demo ,依赖于YYModel ,自己不想用第三方库,那就要一个个的写编码解码,或者使用runtime键值映射稍微简单点儿,我这里不重复造轮子了.
#import <Foundation/Foundation.h>
#import "YYModel.h"
@interface Person : NSObject<NSCoding, NSCopying>
@property (nonatomic,copy) NSString *name;
@property (nonatomic,copy) NSString *age;
@end
#import "Person.h"
@implementation Person
//重写以下几个方法
- (void)encodeWithCoder:(NSCoder*)aCoder {
[self yy_modelEncodeWithCoder:aCoder];
}
- (id)initWithCoder:(NSCoder*)aDecoder
{
self = [super init];
return [self yy_modelInitWithCoder:aDecoder];
}
- (id)copyWithZone:(NSZone*)zone {
return [self yy_modelCopy];
}
- (NSUInteger)hash {
return [self yy_modelHash];
}
- (BOOL)isEqual:(id)object {
return [self yy_modelIsEqual:object];
}
@end
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
#import "ViewController.h"
#import "Person.h"
#define KDocumentPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) lastObject]
#define kPersonInfoPath [KDocumentPath stringByAppendingPathComponent:@"personInfo.archiver"]
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//先存档 然后屏蔽这段代码 看看是否归档到了本地
// NSMutableArray *dataArray =[NSMutableArray array];
//
// for (NSInteger i = 10; i < 20 ; i++) {
// Person * p =[Person new];
// p.name = [NSString stringWithFormat:@"name==-%ld",i];
// p.age = [NSString stringWithFormat:@"+++%ld岁",i];
// [dataArray addObject:p];
// }
//
// BOOL ret = [NSKeyedArchiver archiveRootObject:dataArray toFile:kPersonInfoPath];
//
// if (ret) {
// NSLog(@"归档成功");
// }else{
// NSLog(@"归档失败");
// }
NSArray *arr =[NSKeyedUnarchiver unarchiveObjectWithFile:kPersonInfoPath];
for (Person *p in arr) {
NSLog(@"名字%@,年龄%@", p.name,p.age);
}
}
@end