2010-07-01 46 views
2

我writeToFile沒有保存我的數據到我的.plist。iphone - writeToFile不保存新條目到plist

- (IBAction)clickBtnDone:(id) sender { 
NSLog(@"Done"); 
if ([txtGroupName.text length] > 0) { 
    [self dismissModalViewControllerAnimated:YES]; 
    NSLog(@"Group Name: %@", txtGroupName.text); 
    NSMutableArray *newDict = [[NSMutableArray alloc] init]; 
    [self.groups setObject:newDict forKey:txtGroupName.text]; 
    NSLog(@"Count:%d", [self.groups count]); 

    BOOL success = [self.groups writeToFile:self.groupPath atomically:YES]; 
    if(success) { 
    NSLog(@"Success Saving New Group"); 
    } else { 
    NSLog(@"Failure Saving New Group"); 
    } 
    [newDict release]; 
} 
} 

下面是調試顯示:

2010-07-01 00:48:38.586 Contacts[7111:207] Done 
2010-07-01 00:48:38.589 Contacts[7111:207] Group Name: C 
2010-07-01 00:48:38.590 Contacts[7111:207] Count:3 
2010-07-01 00:48:38.592 Contacts[7111:207] Success Saving New Group 

然而,當我打開的.plist文件,它仍然只有2個,我已經手動創建的組,而不是新的條目。

這些文件位於我的〜Documents文件夾中。

任何想法?

+0

什麼是羣路徑,你能打印出來嗎? – vodkhang 2010-07-01 08:15:42

+0

NSString * path = [[NSBundle mainBundle] pathForResource:@「Groups」ofType:@「plist」]; self.groupPath = path; – john 2010-07-01 08:22:55

+0

看起來它是寫給:/用戶/我/圖書館/應用程序支持/ iPhone模擬器/ 4.0 /應用程序/.../ Groups.plist 有沒有一種方法,我可以把它保存到.plist是在我的工作空間? – john 2010-07-01 08:30:03

回答

3

你是如何初始化groupPath的?它應該是文檔目錄的路徑,而不是資源目錄的路徑。

你應該做同樣的事情:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:FILE_NAME]; 

不能編輯存在於工作區中的文件。

0
NSString* plistPath = nil; 
NSFileManager* manager = [NSFileManager defaultManager]; 
if ((plistPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"PathTo.plist"])) 
    { 
    if ([manager isWritableFileAtPath:plistPath]) 
    { 
     NSMutableDictionary* infoDict = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath]; 
     [infoDict setObject:@"foo object" forKey:@"fookey"]; 
     [infoDict writeToFile:plistPath atomically:NO]; 
     [manager setAttributes:[NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate] ofItemAtPath:[[NSBundle mainBundle] bundlePath] error:nil]; 
    } 
    }