2013-06-30 52 views
0

我在我的xcode項目中有文本文件text.txt,我需要從我的iOS應用程序編寫NSString init。我試過這個代碼ipad - 將NSString寫入文本文件

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *docDir = [paths objectAtIndex: 0]; 
NSString *docFile = [docDir stringByAppendingPathComponent: @"text.txt"]; 
NSString *content = @"Test"; 
[content writeToFile: docFile atomically: NO]; 

但它不爲我工作......所以,你能幫助我嗎?

+0

看起來不錯。我現在不能測試。嘗試刪除'.txt' ... –

+0

看看堆棧的答案:http://stackoverflow.com/questions/5619719/write-a-file-on-ios –

+0

我不知道,有什麼問題...我有text.txt在Xcode的Resources文件夾中,當我嘗試閱讀它時,它是可以的,但是當我想寫一些新的init時,它不起作用... :-(請問你有什麼解決方案嗎? – stepik21

回答

0

這個工作對我來說

//Method writes a string to a text file 
-(void) writeToTextFile{ 
     //get the documents directory: 
     NSArray *paths = NSSearchPathForDirectoriesInDomains 
      (NSDocumentDirectory, NSUserDomainMask, YES); 
     NSString *documentsDirectory = [paths objectAtIndex:0]; 

     //make a file name to write the data to using the documents directory: 
     NSString *fileName = [NSString stringWithFormat:@"%@/text.txt", 
                 documentsDirectory]; 
     //create content - four lines of text 
     NSString *content = @"Test"; 
     //save content to the documents directory 
     [content writeToFile:fileName 
         atomically:NO 
           encoding:NSStringEncodingConversionAllowLossy 
             error:nil]; 

} 
+0

不要使用'stringWithFormat:'來建立路徑,使用'NSString * filename = [documentsDirectory stringByAppendingPathComponent:@「text.txt」]; – rmaddy