1.歸檔方式
把記錄保存在應(yīng)用沙盒的某一文件中研叫,進(jìn)行歸檔锤窑,或者說存檔渊啰。
新建一個類CJSearchRecord申屹,繼承NSObject,并遵守NSCoding協(xié)議
CJSearchRecord.h文件
@interface CJSearchRecord : NSObject<NSCoding>
@property (nonatomic, copy) NSString *beginCity;
@property (nonatomic, copy) NSString *endCity;
CJSearchRecord.m文件實(shí)現(xiàn)兩個方法
//歸檔、存入檔案
-(void)encodeWithCoder:(nonnull NSCoder *)encoder{
[encoder encodeObject:_beginCity forKey:@"beginCity"];
[encoder encodeObject:_endCity forKey:@"endCity"];
}
//解檔嚷那,打開檔案
-(nullable instancetype)initWithCoder:(nonnull NSCoder *)decoder{
if (self=[super init]) {
_beginCity = [decoder decodeObjectForKey:@"beginCity"];
_endCity =[decoder decodeObjectForKey:@"endCity"];
}
return self;
}
在ViewController.m文件中導(dǎo)入上面創(chuàng)建的文件
在某一個按鈕事件方法中
//歸檔杆煞,保存搜索記錄
CJSearchRecord *record = [[CJSearchRecord alloc]init];
//設(shè)置值
record.beginCity = self.beginCity.titleLabel.text;
record.endCity = self.endCity.titleLabel.text;
//獲取沙盒中的document目錄
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
//拼接文件路徑
NSString *filePath = [path stringByAppendingPathComponent:@"searchRecoder.plist"];
//進(jìn)行歸檔
[NSKeyedArchiver archiveRootObject:record toFile:filePath];
在viewDidLoad方法中
//解檔,讀檔,讀取記錄
//獲取文件路徑
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
NSString *filePath = [path stringByAppendingPathComponent:@"searchRecoder.plist"];
CJSearchRecord *record = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];