[問題] iphone上將檔案寫入的問題

看板MacDev作者 (肉元,吉米,助教)時間15年前 (2010/08/16 23:52), 編輯推噓2(2016)
留言18則, 4人參與, 最新討論串1/1
我有一段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

08/17 01:15, , 1F
可能是延遲寫入的關係吧..第二次執行的情況咧?
08/17 01:15, 1F

08/17 07:26, , 2F
第二次的狀況也是一樣QQ
08/17 07:26, 2F

08/17 09:26, , 3F
找到問題了,在loginInfoFilePath那邊的append string應該是
08/17 09:26, 3F

08/17 09:26, , 4F
@"/loginInfo.plist"
08/17 09:26, 4F

08/17 12:17, , 5F
如果是處理路徑的話,用stringByAppendingPathComponent:
08/17 12:17, 5F

08/17 22:12, , 6F
可是我就是用stringByAppend...啊 QQ
08/17 22:12, 6F

08/17 22:50, , 7F
不一樣耶
08/17 22:50, 7F

08/17 22:50, , 8F
append string 有幾個不同的 method
08/17 22:50, 8F

08/17 22:51, , 9F
直接 append 一個 string,用 stringByAppendingString:
08/17 22:51, 9F

08/17 22:52, , 10F
目錄後面接檔名,是stringByAppendingPathComponent:
08/17 22:52, 10F

08/17 22:52, , 11F
檔名後面加附檔名,是stringByAppendingPathExtension:
08/17 22:52, 11F

08/17 22:53, , 12F
而你用的是 stringByAppendingFormat: 而你這樣寫很危險
08/17 22:53, 12F

08/17 22:53, , 13F
因為這個 method 是讓你用一個格式把資料填進去的
08/17 22:53, 13F

08/17 22:54, , 14F
例如 stringBy.,,:@"%@ %d", stringValue, intValue
08/17 22:54, 14F

08/17 22:54, , 15F
但是你後面又沒有加上要供 format 字串用的參數
08/17 22:54, 15F

08/17 22:55, , 16F
這樣假如你的字串裡頭有 %@, %d 這些東西,都會出問題
08/17 22:55, 16F

08/18 00:41, , 17F
喔喔喔!受教了! 感謝~~~
08/18 00:41, 17F

10/17 15:42, , 18F
推薦這一篇
10/17 15:42, 18F
文章代碼(AID): #1CQLwghD (MacDev)
文章代碼(AID): #1CQLwghD (MacDev)