iPad应用程序 - 生成文本文件

时间:2012-02-13 04:44:45

标签: objective-c ios ipad

有人可以解释并提供示例代码,以便在我的iPad应用中执行以下步骤:

  1. 在我的应用中做一些事情,它会生成一些数据(作为字符串)
  2. 将该数据写入文本文件
  3. 能够将我的iPad插入计算机并关闭这些文本文件
  4. 我该怎么做?

1 个答案:

答案 0 :(得分:3)

要在文件中写入字符串,请使用此

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];

然后在plist文件中将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"];
}