歸檔這種存儲(chǔ)方式,比較輕量和高效的. 之前不怎么使用,現(xiàn)在用起來(lái)了,幾個(gè)筆記也好! 以下是隨手寫(xiě)的一個(gè)示例Demo ,依賴(lài)于YYModel ,自己不想用第三方庫(kù),那就要一個(gè)個(gè)的寫(xiě)編碼解碼,或者使用runtime鍵值映射稍微簡(jiǎn)單點(diǎn)兒,我這里不重復(fù)造輪子了.
#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
//重寫(xiě)以下幾個(gè)方法
- (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