2012-02-13 63 views
0

有人能解釋並給出示例代碼做在我的iPad應用程序下面的步驟:iPad應用程序 - 生成文本文件

  1. 做一些事情在我的應用程序,從而產生一些數據(字符串)
  2. 寫數據到一個文本文件
  3. 能在我的iPad插上我的電腦,並抓住這些文本文件從

我怎樣才能做到這一點?

回答

3

對於您的plist文件在文件中使用的字符串寫入此

NSString *str = @"your string"; 
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString* documentsDirectory = [paths objectAtIndex:0]; 
NSString* filePath = [documentsDirectory stringByAppendingPathComponent:@"data.txt"]; 
NSError *error; 
[str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error]; 

然後設置Application supports iTunes file sharing關鍵YES
當你從那裏的iTunes連接您的設備,您可以保存您的data.txt
Here is the video how to get files from iTunes




編輯的要求。

NSUserDefaults *deflt = [NSUserDefaults standardUserDefaults]; 
//this number file is saved, I'm not saving the file name as data0.txt. 
//The first file to be saved is data1.txt 
int num = [deflt integerForKey:@"fileNameNum"]; 
num++; 
NSString *fileName = [NSString stringWithFormat:@"data%d.txt",num];; 
NSString *str = @"your string"; 
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString* documentsDirectory = [paths objectAtIndex:0]; 
NSString* filePath = [documentsDirectory stringByAppendingPathComponent:fileName]; 
NSError *error = nil; 
[str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error]; 
if (error == nil) { 
    //Save the number of the file that you have save in doc directory 
    [deflt setInteger:num forKey:@"fileNameNum"]; 
} 
+0

@StanLe ..我已經編輯我的答案,並增加了一個視頻鏈接,以顯示如何從iTunes獲得的文件。我知道這你會得到這個問題:) – 2012-02-13 05:07:24

+0

真棒。效果很好。現在......另一件事。假設我在我的應用程序中有一個名爲「Data」的文件夾,並且在該文件夾中,每次使用該應用程序時基本上都會保存一個文本文件DataFileX.txt(其中X是一個從1開始的整數)。我怎麼才能找出下一個使用的名字。例如,如果我只保存到Data/DataFile12.txt,那麼我應該保存到Data/DataFile13.txt。你能更新你的代碼來反映這個嗎?謝謝!! – StanLe 2012-02-13 05:08:24

+0

我已經更新了答案 – 2012-02-13 05:22:48