在iOS開(kāi)發(fā)中,需要把用戶(hù)的數(shù)據(jù)存儲(chǔ)起來(lái),便于下次使用,就需要用到數(shù)據(jù)存儲(chǔ)方法.
1.plist存儲(chǔ)
好處:可以手動(dòng)管理存儲(chǔ)路徑,避免系統(tǒng)刪除.
缺點(diǎn):存取都比較繁瑣,不能存儲(chǔ)對(duì)象.
存:
//創(chuàng)建數(shù)據(jù)
NSArray *arr = @[@123,@"dl"];
//獲取存儲(chǔ)路徑
NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
//給路徑加上擴(kuò)展名
path = [path stringByAppendingPathComponent:@"arr.pilst"];
//寫(xiě)入路徑
[arr writeToFile:path atomically:YES];
取:
//獲取存儲(chǔ)路徑
NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
//給路徑加上擴(kuò)展名
path = [path stringByAppendingPathComponent:@"arr.pilst"];
//讀取文件
[NSArray arrayWithContentsOfFile:path];
2.偏好設(shè)置存儲(chǔ)
好處:不需要關(guān)心存儲(chǔ)路徑.
缺點(diǎn):系統(tǒng)管理,程序猿無(wú)法手動(dòng)管理,不能存儲(chǔ)對(duì)象
存:
//獲取系統(tǒng)對(duì)象
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//存儲(chǔ)數(shù)據(jù)
[defaults setObject:name forKey:@"name"];
** 取:**
//定義屬性接收讀取的內(nèi)容
NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:@"name"];
3.自定義對(duì)象存儲(chǔ)
好處:可以存儲(chǔ)任意內(nèi)容,且手動(dòng)管理路徑.
缺點(diǎn):需要實(shí)現(xiàn)很多方法,比較繁瑣.
存:
1.在點(diǎn)擊存儲(chǔ)時(shí)將數(shù)組數(shù)據(jù)歸檔存儲(chǔ):
//使用自定義歸檔實(shí)現(xiàn)通訊錄內(nèi)容數(shù)據(jù)的存儲(chǔ)
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
AddViewController *vc = segue.destinationViewController;
vc.block = ^(DLContact *contact){
[_contacts addObject:contact];
//獲取路徑
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"contact.data"];
NSLog(@"%@",path);
//歸檔內(nèi)容
[NSKeyedArchiver archiveRootObject:_contacts toFile:path];
[self.tableView reloadData];
};
}
2.在模型類(lèi)中重寫(xiě)encodeWithCoder:和initWithCoder:方法給需要?dú)w檔和解檔的模型屬性設(shè)置歸檔和接檔
存取方法實(shí)現(xiàn):
//歸檔成員屬性并設(shè)置其對(duì)應(yīng)的key
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:_name forKey:@"name"];
[aCoder encodeObject:_phone forKey:@"phone"];
}
//根據(jù)key解檔數(shù)據(jù)并賦值給成員變量
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{//需先初始化父類(lèi)
if (self = [super init]) {
_name = [aDecoder decodeObjectForKey:@"name"];
_phone = [aDecoder decodeObjectForKey:@"phone"];
}
return self;
}
3.在數(shù)組懶加載方法中讀取解檔后的數(shù)據(jù)
取:
- (NSMutableArray *)contacts{
//如果沒(méi)有值
if (_contacts == nil) {
//獲取存儲(chǔ)的路徑
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"contact.data"];
//給數(shù)組賦值
_contacts = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
//如果解檔后無(wú)數(shù)據(jù)
if (_contacts == nil) {
//新建數(shù)組準(zhǔn)備存值
_contacts = [NSMutableArray array];
}
}
return _contacts;
}
注意:如果對(duì)模型屬性進(jìn)行了編輯,需再次存檔之后才能讀取到新的模型數(shù)據(jù)!
Tips:可將存檔方法定義為block代碼塊方便及時(shí)調(diào)用.