2011-10-19 48 views
3

我在plist中保存了很多信息。這一個是在我的mainBundle標準。無法保存plist。路徑不可寫

這是我從plist中加載路徑和數據的方法。如果「應用程序支持」文件夾中的文件不存在,我將它從mainBundle複製到那裏。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
self.plistPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",plistName]]; 


NSFileManager *fileManager = [NSFileManager defaultManager]; 

if (![fileManager fileExistsAtPath: self.plistPath]) 
{ 
    NSString *pathInBundle = [[NSBundle mainBundle] pathForResource:plistName ofType:@"plist"]; 
    self.plist = [NSMutableDictionary dictionaryWithContentsOfFile:pathInBundle]; 
    NSLog(@"plist doesnt exist"); 
} 
else { 
    self.plist = [NSMutableDictionary dictionaryWithContentsOfFile:self.plistPath]; 
    NSLog(@"plist exist"); 
} 
NSLog(@"plist path: %@",self.plistPath); 

,如果我在最後添加以下行,這裏只有NO答案:

if([fileManager isWritableFileAtPath:self.plistPath]) NSLog(@"YES"); 
else NSLog(@"NO"); 

畢竟,我試圖挽救與[self.plist writeToFile:self.plistPath atomically:YES];,也不能正常工作。


抱歉回答這麼晚 - 我有很多其他的事情要做。回到我的問題:我只是得到錯誤,當我嘗試添加一個新的條目到我的字典(plist)。編輯是沒有問題的。我認爲問題是,我如何嘗試添加條目。我的代碼如下所示:

NSMutableDictionary *updateDict = [[self.plist objectForKey:@"comments"]mutableCopy]; 

NSMutableDictionary *tmpDict = [[[NSMutableDictionary alloc]init]autorelease]; 
[tmpDict setObject:comment forKey:@"comment"]; 
[tmpDict setObject:author forKey:@"author"]; 
[tmpDict setObject:car forKey:@"car"]; 
[tmpDict setObject:part forKey:@"part"]; 
[tmpDict setObject:date forKey:@"date"]; 

[updateDict setObject:tmpDict forKey:[NSNumber numberWithInt:[updateDict count]+1]]; 

[self.plist setObject:updateDict forKey:@"comments"]; 
if([self.plist writeToFile:self.plistPath atomically:YES]) { 
    return YES; 
} 
else { 
    return NO; 
} 

self.plist是我在plistPath中的本地文件副本。我的plist的結構是這樣的:https://img.skitch.com/20111026-tcjxp9ha4up8ggtfjy7ucgqcqe.png

希望這有助於

+1

這是用於Mac OS X應用程序還是iOS應用程序? –

+0

這是一個iOS應用程序(4.3 iPad) – Adrian

+0

如果您想爲您的問題添加其他信息,只需編輯您的問題(點擊您的問題下方的「編輯」鏈接)。要評論您收到的答案,請使用答案下的評論設施。如果您發現評論空間不足,您應該進行編輯。答案應該就是這樣,直接回答你的問題。 –

回答

1

好了,這不是Documents目錄和iOS不具備默認情況下在沙箱中創建的應用程序支持的目錄,這就是爲什麼你可以不寫。

你可以改變你的方法調用來查找真正的文件目錄:

NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

或者,你得到的路徑應用支持目錄後,必須檢查是否存在已經如果沒有,創建它。

0

請通過previous post,它顯示了從mainBundle複製plist的不同方法。改用[fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];方法。

+0

謝謝。那工作。 – Adrian

+0

歡迎並接受答案... – DShah

+0

現在該文件夾是可寫的。 我證明: '[fileManager isWritableFileAtPath:self.plistPath]' 但我仍然無法保存plist: 'if([self.plist writeToFile:self。原子級的plistPath:YES]){NSFR(@「save ok」); 返回YES; } 其他{ NSLog(@「save failed」); return NO; }' – Adrian

0

找到答案?如果沒有,你需要改變這一行:

[updateDict setObject:tmpDict forKey:[NSNumber numberWithInt:[updateDict count]+1]]; 

[updateDict setObject:tmpDict forKey:[NSString stringWithFormat:@"%d",[updateDict count]+1]]; 

鍵值名稱字符串,而不是反對。