2012-04-14 66 views
1

當我嘗試此代碼:的plist不會寫入文件

if ([[NSFileManager defaultManager] fileExistsAtPath:@"~/Library/Application Support/Staying Afloat/stats/static-stats.plist"] == NO) { 
    NSMutableDictionary* tempDict = [[NSMutableDictionary alloc]initWithObjectsAndKeys: 
            [[NSString alloc] initWithString:@"0"],@"completedGames", 
            [[NSString alloc] initWithString:@"0"],@"floatsCollected", 
            [[NSString alloc] initWithString:@"0"],@"sec", 
            [[NSString alloc] initWithString:@"0"],@"subScore", 
            [[NSString alloc] initWithString:@"0"],@"highScore", 
            [[NSString alloc] initWithString:@"0"],@"longestSec", nil]; 

    [tempDict writeToFile:@"~/Library/Application Support/Staying Afloat/stats/static-stats.plist" atomically:YES]; 

    NSLog(@"written file"); 

} 

,這與輸出

2012-04-14 19:15:10.009 Staying Afloat[3227:9c07] written file 

所以在循環運行,但該文件沒有寫? 任何人都可以指出我在正確的方向拯救plists到非本地化的地方嗎?

編輯:這是Mac

+0

做直播「保持水平/統計/」存在? – 2012-04-14 07:35:07

+1

你可以嘗試'writeToFile:options:error:'得到錯誤信息... – jtbandes 2012-04-14 07:37:20

+0

@jonas:它不存在 – ExceptionSlayer 2012-04-14 07:51:45

回答

6

您需要使用-(NSString *)stringByExpandingTildeInPath當你寫,並檢查文件是否存在,擴大你的路徑。

編輯:在NSDictionary文檔中閱讀方法writeToFile:automatically。它說

If path contains a tilde (~) character, you must expand it with stringByExpandingTildeInPath before invoking this method.

所以才這樣做

[tempDict writeToFile:[[NSString stringWithString:@"~/Library/Application Support/Staying Afloat/stats/static-stats.plist"] stringByExpandingTildeInPath] atomically:YES];
1

第一,你不能只是寫:

[tempDict writeToFile:@"~/Library/Application Support/Staying Afloat/stats/static-stats.plist" atomically:YES]; 

NSLog(@"written file"); 

,因爲你不檢查文件是否真的成功寫入或不。

你應該寫:

if([tempDict writeToFile:@"~/Library/Application Support/Staying Afloat/stats/static-stats.plist" atomically:YES]) { 
    NSLog(@"written file"); 
} else { 
    NSLog(@"file not written"); 
} 

將writeToFile方法返回一個布爾值。

+0

它返回「文件沒有寫入」 – ExceptionSlayer 2012-04-14 22:40:59

0

我總是使用NSUserDefaults,它爲用戶提供諸如用戶自選或在運行之間存儲應用程序狀態等功能。關於我的頭頂,我建議你沒有合適的權利來寫一個plist,如果你不小心摧毀了os的關鍵和價值會發生什麼?看看

Best practices for handling user preferences in an iPhone MVC app?

+3

閱讀標籤,他這樣做的Mac,而不是iOS。 – TheAmateurProgrammer 2012-04-14 07:48:03

+1

-1,它是關於MacOS的! – 2012-04-14 07:59:56

+0

糟糕。也許我不應該用小屏幕來回答問題!我的錯。 – Todd 2012-04-14 10:17:51

0

你肯定-writeToFile:atomically:回報YES

+0

它適用於iOS,右鍵點擊'writeToFile'並閱讀簡短描述。如果文件寫入成功則返回YES,否則返回NO。 – JScarry 2013-06-13 20:03:23

+0

我並不是說它不能或不會返回YES。只是你應該檢查像NSLog(@「%d」,[... writeToFile:atomically:]); – 2013-06-23 07:00:14