一、什么是數(shù)據(jù)持久化
數(shù)據(jù)持久化及數(shù)據(jù)的永久存儲(chǔ),將數(shù)據(jù)保存在硬盤中,程序關(guān)閉,內(nèi)存釋放后,重新打開(kāi)程序,可以繼續(xù)訪問(wèn)之前保存的數(shù)據(jù)。
二、數(shù)據(jù)持久化方式
常見(jiàn)的數(shù)據(jù)持久化方式有以下幾項(xiàng):
沙盒
PReference
歸檔 / 反歸檔
SQLite
CoreData
這篇只講沙盒,preference,歸檔/反歸檔。
1.沙盒
沙盒是系統(tǒng)為每一個(gè)應(yīng)用程序生成的一個(gè)特定文件夾 文件夾的名字由十六進(jìn)制數(shù)據(jù)組成,每一個(gè)應(yīng)用程序的沙盒文件名都是不一樣的,是由系統(tǒng)隨機(jī)生成的。
//獲取沙盒主目錄 NSString *path = NSHomeDirectory(); NSLog(@"%@",path);
沙盒下每個(gè)文件夾的路徑及作用
//Documents 存放的一些比較重要的文件,但是存入Documents中的文件不能過(guò)大 //如何獲取Documents文件目錄 NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; NSLog(@"%@",documentsPath); //用firstobject取值是因?yàn)?/span>該方法一開(kāi)始使用mac端OS X開(kāi)發(fā),對(duì)于PC端用戶可以有多個(gè)用戶,所以可以取到很多user的路徑,但是該方法現(xiàn)在用于手機(jī)開(kāi)發(fā),手機(jī)端只有一個(gè)用戶,所以獲得的用戶只有一個(gè),lastobject也是可以的。 //Library:是一個(gè)資源庫(kù),存儲(chǔ)一些不太重要的數(shù)據(jù),相對(duì)比較大一些,里邊有兩個(gè)子文件夾; NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)firstObject]; //Caches:緩存文件,圖片緩存,音頻,視頻。網(wǎng)頁(yè)資源。應(yīng)用程序清除緩存,就是清除該文件夾 NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject]; //Preferences:系統(tǒng)偏好設(shè)置,用戶對(duì)應(yīng)程序的設(shè)置,比如用戶名和用戶密碼,preference路徑無(wú)法找到,通過(guò)NSUserDefaults //temp:存放臨時(shí)文件,比如下載的壓縮包zip,解壓后理解把壓縮包刪除 NSString *tempPath = NSTemporaryDirectory(); NSLog(@"%@",tempPath); //bundle:ios8之前,包和沙河在同一個(gè)目錄下,之后.app單獨(dú)存儲(chǔ)到一個(gè)獨(dú)立的文件目錄下。 .app 文件 readOnly。從appStore下載下來(lái)的是這個(gè)包,程序上傳的時(shí)候也是這個(gè)包 NSString *bundlepath = [[NSBundle mainBundle] bundlePath]; NSLog(@"%@",bundlepath);
// NSSearchPathDirectory 這個(gè)類是用來(lái)查找文件目錄的 //第一個(gè)參數(shù):文件名稱 //第二個(gè)參數(shù),確定搜索域 //第三個(gè)參數(shù):確定相對(duì)路徑還是絕對(duì)路徑。YES絕對(duì),NO相對(duì)
文件相關(guān)操作
/** * 文件刪除 */- (void)deleteFile { NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]; NSString *imagePath = [cachesPath stringByAppendingPathComponent:@"iamge"]; NSLog(@"%@",imagePath); //創(chuàng)建文件管理者 NSFileManager *fileManager = [NSFileManager defaultManager]; //判斷文件是否存在 BOOL isExist = [fileManager fileExistsAtPath:imagePath]; if (!isExist) { BOOL isSuccess = [fileManager createDirectoryAtPath:imagePath withIntermediateDirectories:YES attributes:nil error:nil]; NSLog(@"%@",isSuccess ? @"創(chuàng)建成功" : @"創(chuàng)建失敗"); } //刪除文件 if ([fileManager fileExistsAtPath:imagePath]) { BOOL isSucess = [fileManager removeItemAtPath:imagePath error:nil]; NSLog(@"%@",isSucess ? @"刪除成功" : @"刪除失敗"); }}
/** * 移動(dòng) */- (void)moveFile { NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]; NSString *imagePath = [cachesPath stringByAppendingPathComponent:@"iamge"]; NSLog(@"%@",imagePath); //創(chuàng)建文件管理者 NSFileManager *fileManager = [NSFileManager defaultManager]; //判斷文件是否存在 BOOL isExist = [fileManager fileExistsAtPath:imagePath]; if (!isExist) { BOOL isSuccess = [fileManager createDirectoryAtPath:imagePath withIntermediateDirectories:YES attributes:nil error:nil]; NSLog(@"%@",isSuccess ? @"創(chuàng)建成功" : @"創(chuàng)建失敗"); } //刪除文件 // if ([fileManager fileExistsAtPath:imagePath]) { // BOOL isSucess = [fileManager removeItemAtPath:imagePath error:nil]; // NSLog(@"%@",isSucess ? @"刪除成功" : @"刪除失敗"); // } //拷貝文件 // 把包中的plist文件拷貝到image文件夾下 NSString *plistInBundlePath = [[NSBundle mainBundle] pathForResource:@"NB.plist" ofType:nil]; NSString *nBPath = [imagePath stringByAppendingPathComponent:@"NB.plist"]; // 拷貝, if (![fileManager fileExistsAtPath:nBPath]) { BOOL isSuccess = [fileManager copyItemAtPath:plistInBundlePath toPath:nBPath error:nil]; NSLog(@"%@",isSuccess ? @"拷貝成功" : @"拷貝失敗"); } NSString *toPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject]; BOOL isSuccess = [fileManager moveItemAtPath:nBPath toPath:[toPath stringByAppendingPathComponent:@"NB.plist"] error:nil]; NSLog(@"%@",isSuccess ? @"移動(dòng)成功" : @"移動(dòng)失敗"); }
//字符串寫入文件- (void)writeToFile { //簡(jiǎn)單對(duì)象寫入文件:字符串,數(shù)組,字典,二進(jìn)制流 只有這些簡(jiǎn)單對(duì)象支持文件的寫入 //如果要寫入的文件數(shù)據(jù)時(shí)數(shù)組,字典,必須要保證數(shù)組,字典中的數(shù)據(jù) 也是簡(jiǎn)單對(duì)象(如果是復(fù)雜對(duì)象,請(qǐng)參照后邊的歸檔,反歸檔) //將字符串寫入Documents文件夾下 NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject]; NSString *toPath = [documentsPath stringByAppendingPathComponent:@"string.txt"]; NSString *string = @"string-string-string-"; //第一個(gè)參數(shù),要寫入的文件路徑,如果不存在文件,會(huì)自動(dòng)創(chuàng)建 第二個(gè)參數(shù),原子性,判斷是否需要生成輔助文件,保護(hù)在多線程下安全 第三個(gè)參數(shù),編碼格式 第四個(gè)參數(shù),錯(cuò)誤信息 NSError *error = nil; BOOL isSuccess = [string writeToFile:toPath atomically:YES encoding:NSUTF8StringEncoding error:&error]; NSLog(@"%@",isSuccess ? @"寫入成功" : @"寫入失敗"); NSString *str = [NSString stringWithContentsOfFile:toPath encoding:NSUTF8StringEncoding error:nil]; NSLog(@"%@",str);}
//數(shù)組寫入文件- (void)writeArray { NSString *str = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)firstObject]; NSString *toPath = [str stringByAppendingPathComponent:@"array.txt"]; NSArray *array = @[@"123",@"123"]; BOOL isSuccess = [array writeToFile:toPath atomically:YES]; NSLog(@"%@",isSuccess ? @"寫入成功" : @"寫入失敗"); NSArray *arr = [NSArray arrayWithContentsOfFile:toPath]; NSLog(@"%@",arr);}
//字典寫入文件- (void)writeDic { NSDictionary *dic = @{@"key":@"value"}; NSString *str = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject]; NSString *toPath = [str stringByAppendingPathComponent:@"dictonry.txt"]; BOOL isSuccess = [dic writeToFile:toPath atomically:YES]; NSLog(@"%@",isSuccess ? @"成功" : @"失敗"); NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:toPath]; NSLog(@"%@",dict);}
//NSData寫入文件- (void)writeData { NSString *tempPath = NSTemporaryDirectory(); NSString *toPath = [tempPath stringByAppendingPathComponent:@"data.txt"]; NSString *string = @"datadata"; NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; BOOL isSuccess = [data writeToFile:toPath atomically:YES]; NSLog(@"%@",isSuccess ? @"成功" : @"失敗"); NSData *getData = [NSData dataWithContentsOfFile:toPath]; NSString *str = [[NSString alloc] initWithData:getData encoding:NSUTF8StringEncoding]; NSLog(@"%@",str);}
2.preference
//Preference- (void)writeToPreference { // NSUserDefaults 繼承自NSObject ,單例 通過(guò)kvc模式賦值 NSLog(@"%@",NSHomeDirectory()); //創(chuàng)建用戶索引對(duì)象 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setInteger:100 forKey:@"money"]; //立即同步操作 對(duì)preference中的文件進(jìn)行修改后,立即同步 [defaults synchronize]; NSInteger money = [defaults integerForKey:@"money"]; NSLog(@"%ld",money); [defaults setInteger:10000 forKey:@"MyMoney"]; [defaults synchronize]; NSInteger you = [defaults integerForKey:@"you"]; NSLog(@"%ld",(long)you); if (money < 10) { NSLog(@"there is no money"); } else { NSLog(@"-100"); money -= 100; [defaults setInteger:40 forKey:@"money"]; [defaults setInteger:1000 forKey:@"YourMoney"]; } // NSUserDefaults 一般存儲(chǔ)一些比較小的數(shù)據(jù),大部分用來(lái)存數(shù)值 //例子:判斷用戶是否第一次登陸 NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; BOOL isFirst = [userDefault boolForKey:@"isFirst"]; [userDefault setBool:YES forKey:@"isFirst"]; [userDefault synchronize]; if (!isFirst) { NSLog(@"第一次登陸"); } else { NSLog(@"不是第一次登陸"); }}
3.歸檔 / 反歸檔
復(fù)雜對(duì)象寫入文件需要使用歸檔 ,讀取需要使用反歸檔,不能直接寫入文件,數(shù)組中有復(fù)雜對(duì)象也要使用歸檔 / 反歸檔
復(fù)雜對(duì)象使用行歸檔和反歸檔,需要遵循NSCoding協(xié)議,并實(shí)現(xiàn)協(xié)議中- (void)encodeWithCoder:(NSCoder *)aCoder; - (id)initWithCoder:(NSCoder *)aDecoder; 兩個(gè)方法
新建Person類
在Person.h中 遵循協(xié)議
//// Person.h// 07.24-DataPersistiser//// Created by lanouhn on 14/7/24.// Copyright (c) 2014年 LCD. All rights reserved.//#import <Foundation/Foundation.h>@interface Person : NSObject <NSCoding>@property (nonatomic, copy) NSString *name;@property (nonatomic, copy) NSString *gender;@property (nonatomic, assign) NSInteger age;@end
在Person.m中實(shí)現(xiàn)協(xié)議方法
//// Person.m// 07.24-DataPersistiser//// Created by lanouhn on 14/7/24.// Copyright (c) 2014年 LCD. All rights reserved.//#import "Person.h"@implementation Person//當(dāng)要?dú)w檔時(shí),對(duì)象會(huì)自動(dòng)觸發(fā)這個(gè)方法- (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:self.name forKey:@"name"]; [aCoder encodeObject:self.gender forKey:@"gender"]; [aCoder encodeObject:@(self.age) forKey:@"age"];}- (id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; if (self) { self.name = [aDecoder decodeObjectForKey:@"name"]; self.gender = [aDecoder decodeObjectForKey:@"gender"]; self.age = [[aDecoder decodeObjectForKey:@"age"] integerValue]; } return self;}@end
歸檔 / 反歸檔
- (void)archiver { //把復(fù)雜文件寫入文件,先轉(zhuǎn)化為nsdata對(duì)象 //歸檔:歸檔的實(shí)質(zhì)就是把其他類型的數(shù)據(jù)(person),先轉(zhuǎn)化為NSData,再寫入文件。 Person *person = [[Person alloc] initWithName:@"rose" gender:@"girl" age:25]; // NSKeyedArchiver 壓縮工具類,繼承自NSCoder,主要用于編碼 NSMutableData *data = [NSMutableData data] ; NSKeyedArchiver *achiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; //使用壓縮工具講Person壓到data中 [achiver encodeObject:person forKey:@"person"]; //完成壓縮,停掉壓縮工具 [achiver finishEncoding]; NSString *homePath = NSHomeDirectory(); NSString *toPath = [homePath stringByAppendingPathComponent:@"person.txt"]; BOOL isSuccess = [data writeToFile:toPath atomically:YES]; NSLog(@"%@",isSuccess ? @"成功" : @"失敗"); //復(fù)雜對(duì)象的讀取,反歸檔 // NSKeyedUnarchiver NSData *getData = [NSData dataWithContentsOfFile:toPath]; NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:getData]; //解壓 Person *p1 = [unArchiver decodeObjectForKey:@"person"]; [unArchiver finishDecoding];}
//集合NSArray NSDictionary 如果想進(jìn)行歸檔和反歸檔,那么它里邊存儲(chǔ)的元素也要遵循NSCoding協(xié)議 Person *person1 = [[Person alloc] initWithName:@"jack" gender:@"男" age:20]; Person *person2 = [[Person alloc] initWithName:@"rose" gender:@"女" age:20]; NSArray *array = @[person1,person2]; NSMutableData *data = [NSMutableData data]; NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; [archiver encodeObject:array forKey:@"array"]; [archiver finishEncoding]; NSString *tmpPath = NSTemporaryDirectory(); NSString *toPath = [tmpPath stringByAppendingString:@"array.txt"]; BOOL isSuccess = [data writeToFile:toPath atomically:YES]; NSLog(@"%@",isSuccess ? @"成功" : @"失敗"); //反歸檔 NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; NSArray *unArchiverArray = [unArchiver decodeObjectForKey:@"array"];
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注