ios數據存儲2016.6

1.歸檔方式

把記錄保存在應用沙盒的某一文件中,進行歸檔,或者說存檔。
新建一個類CJSearchRecord,繼承NSObject,并遵守NSCoding協議
CJSearchRecord.h文件

@interface CJSearchRecord : NSObject<NSCoding>
@property (nonatomic, copy) NSString *beginCity;
@property (nonatomic, copy) NSString *endCity;

CJSearchRecord.m文件實現兩個方法

//歸檔、存入檔案
-(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文件中導入上面創建的文件
在某一個按鈕事件方法中

    //歸檔,保存搜索記錄
    CJSearchRecord *record = [[CJSearchRecord alloc]init];
    //設置值
    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"];
    //進行歸檔
    [NSKeyedArchiver archiveRootObject:record toFile:filePath];

在viewDidLoad方法中

 //解檔,讀檔,讀取記錄
    //獲取文件路徑
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *filePath = [path stringByAppendingPathComponent:@"searchRecoder.plist"];
    CJSearchRecord *record = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容