作者Gsus (肉元,吉米,助教)
看板MacDev
標題[問題] iphone上將檔案寫入的問題
時間Mon Aug 16 23:52:08 2010
我有一段code如下
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
if (paths.count > 0) {
NSString *loginInfoFilePath =
[[paths objectAtIndex:0] stringByAppendingFormat:@"loginInfo.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
// if loginInfo.plist do not exists:
if (![fileManager fileExistsAtPath:loginInfoFilePath]) {
NSDictionary *loginInfoDictionary = [[NSDictionary alloc]
initWithObjectsAndKeys:@"", nicknameKey, @"", passwordKey, nil];
[loginInfoDictionary writeToFile:loginInfoFilePath atomically:YES];
[loginInfoDictionary release];
}
// here loginInfo.plist should always exists
if ([fileManager fileExistsAtPath:loginInfoFilePath]) {
// do something here.
}
上面總共有3個if
我在simulator上測試,app第一次launch時3個if都有跑到
可是換在device上測試的時候,一樣是第一次launch
卻唯獨第3個if跑不進去
問題可能出在writeToFile沒有成功
可是我還不確定
而且另我納悶的是為什麼simulator可以,device卻會有不一樣的結果QQ
是哪邊出問題了嗎~
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 111.251.146.190
推 wasihero:可能是延遲寫入的關係吧..第二次執行的情況咧? 08/17 01:15
→ Gsus:第二次的狀況也是一樣QQ 08/17 07:26
→ Gsus:找到問題了,在loginInfoFilePath那邊的append string應該是 08/17 09:26
→ Gsus:@"/loginInfo.plist" 08/17 09:26
→ zonble:如果是處理路徑的話,用stringByAppendingPathComponent: 08/17 12:17
→ Gsus:可是我就是用stringByAppend...啊 QQ 08/17 22:12
→ zonble:不一樣耶 08/17 22:50
→ zonble:append string 有幾個不同的 method 08/17 22:50
→ zonble:直接 append 一個 string,用 stringByAppendingString: 08/17 22:51
→ zonble:目錄後面接檔名,是stringByAppendingPathComponent: 08/17 22:52
→ zonble:檔名後面加附檔名,是stringByAppendingPathExtension: 08/17 22:52
→ zonble:而你用的是 stringByAppendingFormat: 而你這樣寫很危險 08/17 22:53
→ zonble:因為這個 method 是讓你用一個格式把資料填進去的 08/17 22:53
→ zonble:例如 stringBy.,,:@"%@ %d", stringValue, intValue 08/17 22:54
→ zonble:但是你後面又沒有加上要供 format 字串用的參數 08/17 22:54
→ zonble:這樣假如你的字串裡頭有 %@, %d 這些東西,都會出問題 08/17 22:55
→ Gsus:喔喔喔!受教了! 感謝~~~ 08/18 00:41
推 antirazin:推薦這一篇 10/17 15:42