plist文件寫入Documents目錄注意事項

一、第一種是在沒有plist文件的情況下
    NSDictionary *dict1 = [NSDictionary dictionaryWithObject:@"john1" forKey:@"name1"];
    NSString *path1 = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/user1.plist"];
<span style="color:#FF0000;">// 注意這裏不能使用 NSMutableDictionary *dictPlist1 = [[NSMutableDictionary alloc] initWithContentsOfFile:path1]; 
// 因爲plist文件還不存在,所以初始化後dictPlist1會是空的</span>
    NSMutableDictionary *dictPlist1 = [NSMutableDictionary dictionary];
    [dictPlist1 setValuesForKeysWithDictionary:dict1];
    [dictPlist1 writeToFile:path1 atomically:YES];



二、第二種是在有plist文件的情況下,用於中途插入數據

    NSDictionary *dict2 = [NSDictionary dictionaryWithObject:@"john2" forKey:@"name2"];
    NSString *path2 = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/user2.plist"];
<span style="color:#FF0000;">// 這裏使用不能使用上面那種初始化,那樣會把之前的數據初始化</span>
    NSMutableDictionary *dictPlist2 = [[NSMutableDictionary alloc] initWithContentsOfFile:path2];
    [dictPlist2 setValuesForKeysWithDictionary:dict2];
    [dictPlist2 writeToFile:path2 atomically:YES];


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