2010-11-09 19 views
6

我試圖寫一個清單,包含在我的項目(Deck.txt)一個文本文件中的相關代碼如下:寫入字符串使用的Xcode爲iPhone開發的文本文件

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Deck" ofType:@"txt"]; 
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath]; 
deck = [[NSString alloc]initWithFormat: @"%@\n%@ %@",file, txtQuantity.text, cardName]; 
//[deck writeToFile:filePath atomically:YES encoding:NSStringEncodingConversionAllowLossy error:nil]; 
[fileHandle writeData:[deck dataUsingEncoding:NSUTF8StringEncoding]];     
[fileHandle closeFile]; 

但是,當我運行代碼時,它不會保存到文本文檔中,或者至少不會保存在我的項目中。它仍然會創建列表並從文件中讀取我正在嘗試寫入的所有數據,但是當關閉程序時,不會對文本文檔進行更改。非常感激任何的幫助。

回答

16

如果你已經有了你的NSData實例,你當然可以將數據寫入設備的內置文檔目錄。通過一些搜索,從模擬器運行時檢查位置並不難。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *docDir = [paths objectAtIndex: 0]; 
NSString *docFile = [docDir stringByAppendingPathComponent: @"deck.txt"]; 

//your variable "deck" 
[deck writeToFile: docFile atomically: NO]; 

這肯定會寫入文件目錄中的文件。它應該只是一個改變你的代碼從目錄中讀取的問題。

2

您無法寫入您的捆綁包路徑中的文件。你需要NSDocumentDirectory。

+0

您的鏈接返回此帖。 – achi 2013-07-03 22:45:18

+0

那裏。固定。 ;-) – 2013-07-04 04:41:11

2

設置你的文件路徑與此(作爲一個例子):

NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/dt"]; 

然後將數據存儲這樣的:

[VARNAME writeToFile:filePath atomically:YES (or NO)]; 

我想你正在嘗試做的可以更簡單地像做這個。

相關問題