2013-02-04 25 views
1

我試圖用NSDictionary保存一些用戶設置,但它不工作。NSDictionary writetofile不起作用

我已經檢查了類似的問題,但我無法找出問題所在。

這裏是我的代碼:

NSDictionary *settings; 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES); 
NSString *settingsPath = [NSString stringWithFormat:@"%@/UserSettings.plist", [paths objectAtIndex:0]]; 
BOOL settingsExist = [[NSFileManager defaultManager] fileExistsAtPath:settingsPath]; 
if(settingsExist){ 
    NSLog(@"file found!"); 
    settings = [NSDictionary dictionaryWithContentsOfFile:settingsPath]; 
}else{ 
    NSLog(@"file not found!"); 
    settings = [[NSDictionary alloc] initWithObjectsAndKeys:@"iPhone",@"device", nil]; 
    [[NSFileManager defaultManager] createFileAtPath:settingsPath contents:nil attributes:nil]; 
    if([settings writeToFile:settingsPath atomically:YES]){ 
     NSLog(@"success!"); 
    }else{ 
     NSLog(@"fail!"); 
    } 
} 

它保留返回 '失敗!'。 你能幫我解決這個問題嗎?

+1

我確定你的意思是'NSDocumentDirectory'而不是'NSDocumentationDirectory'。另外,您不得***使用格式字符串來構建文件路徑。爲此,使用'stringByAppendingPathComponent:'。 – 2013-02-04 15:02:00

+0

@ H2CO3啊,終於搞定了!謝謝,我會記住這一點。謝謝:D –

回答

3

您需要指定NSDocumentDirectory而不是NSDocumentationDirectory

+0

謝謝!我正在犯這樣一個新手的錯誤:D –

+0

XCode自動完成首先提供了'不正確的'。從我所看到的情況來看,它可能也會少得多,也就是說,在stackoverflow上對'NSDocumentationDirectory'的引用列表壓倒了這個相同的問題:http://stackoverflow.com/search?q=nsdocumentationdirectory 小而痛苦的錯誤。 –

+1

@marccenedella是的,我自己被那個人燒燬了;很容易錯過。 – jlehr