OC 創建和寫入plist文件

在開發過程中,有時候需要把程序的一些配置保存下來,或者遊戲數據等等。 這時候需要寫入Plist數據。

寫入的plist文件會生成在對應程序的沙盒目錄裏。

接着上面讀取plist數據的代碼,加入了寫入數據的代碼。

    // 文件保存的地址分兩種
    // 1、獲取應用程序沙盒下的Documents目錄(或其它目錄)
    NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *path = [pathArr objectAtIndex:0];
    //得到完整的文件名
    NSString *filePath = [path stringByAppendingPathComponent:@"test.plist"];

    // 2、[NSBundle mainBundle]
    // NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"plist"];
    
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
    NSLog(@"%@", data);
    // 添加一項內容
    [data setObject:@"add some content" forKey:@"c_key"];
    
    // 文件寫入
    if ([data writeToFile:filePath atomically:YES]) {
        NSLog(@"寫入成功");
    } else {
        NSLog(@"寫入失敗");
    }
    
    
    // 那怎麼證明我的數據寫入了呢?讀出來看看
    // 文件讀取
    NSMutableDictionary *data1 = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
    NSLog(@"%@", data1);


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章