天天看點

iOS中的資料持久化,歸檔和反歸檔

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    //列印目前應用程式的沙盒路徑

    NSLog(@"%@", NSHomeDirectory());

    //沙盒:在一定範圍内可以随意做任何事

    //iOS程式的沙盒指的就是應用程式的檔案操作檔案夾, 在檔案夾内可以讀寫任何内容, 但是完全不能通路其他應用程式的沙盒檔案夾

    //Documents:跟使用者相關的一些檔案, 使用者設定的對這個app的偏好設定. 使用者的一些文本資訊. 最好不要存儲空間占用比較大的檔案比如視訊/音頻等等

    //Library:給開發者使用的, 用來存儲一些東西的檔案夾

    //Caches:緩存檔案夾, 使用者看過的一些圖檔, 音頻, 視訊, 都可以存儲在這個檔案夾中.一般的app, 清除緩存意思就是清除這個檔案夾的所有内容

    //Preferences: 給開發者存儲一些内容, NSUserDefaults儲存的資訊都在這個檔案夾中

    //    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:<#(NSString *)#>]

    //tmp:臨時檔案夾, 存儲網絡請求過程中的一些臨時檔案. app版本更新的時候, 會直接清空tmp檔案夾.

    //簡單對象寫入本地

    //NSString, NSNumber, NSDictionary, NSArray, NSData;

    //1.拼接一個存儲路徑

    //系統提供了一個函數, 可以直接傳回某一個沙盒檔案夾的路徑

    //傳回值: 找到的路徑組成的數組, 如果搜尋的是系統的沙盒檔案夾路徑, 數組中隻有一個元素.

    //參數1:搜尋沙盒中的哪個檔案夾

    //參數2:搜尋的範圍

    //參數3:傳回的是相對路徑還是絕對路徑

    NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSLog(@"%@", arr);

    //擷取檔案路徑

    //取出documents檔案夾的路徑

    NSString *docPath = [arr lastObject];

    //拼接一個檔案的路徑

    NSString *txtPath = [docPath stringByAppendingString:@"/123.txt"];

    //2.按照路徑寫入

    NSString *str = @"aa";

    //參數1:要寫入的路徑

    //參數2:是否對寫入的檔案進行寫保護

    //參數3:編碼格式

    //參數4:錯誤資訊

    NSError *error = nil;

    [str writeToFile:txtPath atomically:YES encoding:NSUTF8StringEncoding error:&error];

    //數組寫入本地

    NSArray *array = [NSArray arrayWithObjects:@"a", @"b", @"c", nil];

    NSString *arrPath = [docPath stringByAppendingPathComponent:@"suibian.plist "];

    //寫入本地

    [array writeToFile:arrPath atomically:YES];

    //建立boss對象

    Boss *boss = [[Boss alloc] init];

    boss.name = @"ww";

    boss.number = @"20";

    boss.sex = @"man";

    // 将複雜對象寫入本地的工具

    //參數1:要寫入本地的對象

    //參數2:要寫入的路徑

    NSString *bossPath = [docPath stringByAppendingPathComponent:@"boss.aa"];

    //歸檔類

    BOOL result = [NSKeyedArchiver archiveRootObject:boss toFile:bossPath];

    NSLog(@"複雜對象寫入本地:%d", result);

    [boss release];

    //反歸檔類

    //從本地讀取資料産生一個新的複雜對象

    Boss *bossReturn = [NSKeyedUnarchiver unarchiveObjectWithFile:bossPath];

    NSLog(@"%@", bossReturn.name);

}