數據持久化的步驟
// 1.指定前往哪個文件夾
// 2,用字符串接收路徑
// 3.拼接文件夾路徑
// 4.寫入本地或者歸檔操作
// 注 :如果是複雜對象歸檔 ,要簽訂NSCoding方法 .並且實現兩個協議方法,放在數組裏的複雜對象歸檔也要籤協議
蘋果手機爲了保證自己數據上的絕對的安全設計了沙盒文件 ,每一個應用程序都配備了自己的沙盒文件 ,每一次運行 ,文件夾的名字就會變成一個沒有任何規律的字符串
複雜對象寫入到本地 ,主要至我們自己創建的對象寫入到本地, 也叫歸檔和反歸檔操作
結構體 歸檔與反歸檔
創建對象
Student *stu =[[Student alloc] initWithName:@"11" hobby:@"11" sex:@"11" age:70];
1.通過數組獲取沙盒地址
NSArray *sandBox =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
2.用字符串保存沙盒路徑
NSString *sandBoxPath =sandBox[0];
3.拼接文件夾路徑 ,這個文件的擴展名是任意的
NSString *documentPath =[sandBoxPath stringByAppendingPathComponent:@"學生.avi"];
4.對對象進行歸檔操作
第一個參數 :要試試歸檔的對象
第二個參數 :路徑
[NSKeyedArchiver archiveRootObject:stu toFile:documentPath];
反歸檔
Student *newstu =[NSKeyedUnarchiver unarchiveObjectWithFile:documentPath];
數組歸檔
Student *stu =[[Student alloc] initWithName:@"11" hobby:@"11" sex:@"11" age:70];
Student *stu1 =[[Student alloc] initWithName:@"22" hobby:@"22" sex:@"nan" age:71];
Student *stu2 =[[Student alloc] initWithName:@"33" hobby:@"33" sex:@"nv" age:30];
NSMutableArray *arr =[NSMutableArray arrayWithObjects:stu,stu1,stu2, nil];
NSArray *sandBox =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *sandBoxPath =sandBox[0];
NSString *document=[sandBoxPath stringByAppendingPathComponent:@"xuesheng.avi"];
// 歸檔
[NSKeyedArchiver archiveRootObject:arr toFile:document];
NSLog(@"%@",document);
// 反歸檔
NSArray *newArr =[NSKeyedUnarchiver unarchiveObjectWithFile:document];
for (Student *stu in newArr) {
NSLog(@"%@",stu.name);
}
NSUserDefaults 一般存放的實效的數據,比如字符串等,他用法和字典類似
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setObject:@"12345" forKey:@"password"];
[defaults synchronize];
NSArray *sandBox =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *sandBoxPath =sandBox[0];
NSLog(@"%@",sandBoxPath);
NSLog(@"%@", [defaults objectForKey:@"password"]);
通過文件管理者對文件進行操作
NSArray *sandBox=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES);
NSString *sandBoxPath=sandBox[0];
// 創建一個文件管理者
NSFileManager *manager =[NSFileManager defaultManager];
// 給要創建的文件夾拼接一個路徑
NSString *filePath =[sandBoxPath stringByAppendingPathComponent:@"guyu"];
// 文件夾的名不需要有任何的擴展名
// 通過manager進行文件夾的創建
[manager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
// NSLog(@"%@",filePath);
// 向新創建的文件夾裏寫入一個字符串
NSString *document =[filePath stringByAppendingPathComponent:@"guyu.txt"];
NSString *str =@"11";
[str writeToFile:document atomically:YES encoding:NSUTF8StringEncoding error:nil];
移除文件夾
// [manager removeItemAtPath:filePath error:nil];
// NSLog(@"%@",sandBoxPath);
移除緩存文件
NSArray *scache= NSSearchPathForDirectoriesInDomains(NSCachesDirectory, 1, YES);
NSString *cachePath = scache[0];
[manager removeItemAtPath:cachePath error:nil];
NSLog(@"%@",cachePath);