2010-11-07 108 views
1

我寫了一小段代碼寫入plist文件。我沒有收到XCode的任何錯誤或警告,所以我真的迷失了。在這段代碼中沒有定義「Root」,但它只是從plist中提取的數據字典。如何寫入plist文件?

有沒有人有一個想法,爲什麼這不會寫入plist文件?它從字面上根本不會改變文件。

NSMutableArray *newReports = [[NSMutableArray alloc] init]; 
    newReports = [[Root objectForKey:@"Reports"] mutableCopy ]; 

    //Creating data model for new report 
    NSMutableDictionary *newReport = [[NSMutableDictionary alloc] init]; 

    NSString *tempTitle = titleField.text; 
    NSString *tempEmployee = employeeField.text; 
    NSArray *tempNodes = [[NSArray alloc] init]; 

    [newReport setObject:tempTitle forKey:@"Title"]; 
    [newReport setObject:tempEmployee forKey:@"Employee"]; 
    [newReport setObject:tempNodes forKey:@"Nodes"]; 

    [newReports addObject:newReport]; 

    NSMutableDictionary *newRoot = [[NSMutableDictionary alloc] init]; 

    [newRoot setObject:newReports forKey:@"Reports"]; 

    //Writing data to plist 
    NSString *Path = [[NSBundle mainBundle] bundlePath]; 
    NSString *filePath = [Path stringByAppendingPathComponent:@"data.plist"]; 

    [newRoot writeToFile:filePath atomically: YES]; 

感謝您的幫助!

回答

5

試圖構建這樣

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                 NSUserDomainMask, YES); 
NSString *documentsDirectoryPath = [paths objectAtIndex:0]; 
NSString *filePath = [documentsDirectoryPath 
         stringByAppendingPathComponent:@"data.plist"]; 
[newRoot writeToFile:filePath atomically: YES]; 
+0

感謝您的幫助文件的路徑,但我認爲這個問題是關係到構建newReport - 它原來是一個零值。 – Andrew 2010-11-07 03:20:36

4

如果您在設備上運行此功能,則主包是隻讀的。您需要將此plist編寫到用戶的文檔目錄中。