【问题标题】:Objective-C creating a text file with a stringObjective-C 创建一个带有字符串的文本文件
【发布时间】:2010-12-21 16:04:08
【问题描述】:

我正在尝试在我的桌面上创建一个包含字符串内容的文本文件。我不确定我是否做得对,我没有收到错误,但它也不起作用......

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES);
NSString *desktopDirectory=[paths objectAtIndex:0];
NSString *filename = [desktopDirectory stringByAppendingString: @"file.txt"];
[myString writeToFile:filename atomically:YES encoding: NSUTF8StringEncoding error: NULL];

【问题讨论】:

    标签: objective-c cocoa nsstring save


    【解决方案1】:
    //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:@"%@/textfile.txt", 
                                                      documentsDirectory];
        //create content - four lines of text
        NSString *content = @"One\nTwo\nThree\nFour\nFive";
        //save content to the documents directory
        [content writeToFile:fileName 
                         atomically:NO 
                               encoding:NSStringEncodingConversionAllowLossy 
                                      error:nil];
    
    }
    

    【讨论】:

    • 谢谢,伙计!简单易用。
    • 请注意,NSStringEncodingConversionAllowLossy 不应该在此处使用,它不是字符串编码类型,而是恰好与 NSASCIIStringEncoding (1) 具有相同值的编码选项
    • 我可能会选择NSString *fileName = [documentsDirectory stringByAppendingPathComponent: @"textfile.txt"];
    【解决方案2】:

    问题是桌面目录字符串不以任何结尾(没有 /)。使用 UIAlertview 进行检查(在 iPhone 上)。

    【讨论】:

    • 什么? 1.)如果您按照他的方式进行操作,则无需使用/。 2.) 你在哪里看到 UIAlertView?我不。 3.) 这个问题是在大约 2 年前提出的。
    • ..另外,我们为什么要在 iOS 上查看与“桌面”有关的内容? iOS 没有这样的东西。
    【解决方案3】:

    您不知道您是否收到任何错误,因为您忽略了 -writeToFile:... 方法返回的 YES/NO 值,并且没有给它提供记录任何可能失败的错误指针。如果该方法返回 NO,您将检查(并处理或显示)错误以查看问题所在。

    猜测,失败是由于您构建的路径。尝试使用 -stringByAppendingPathComponent: 而不是 -stringByAppendingString: ... this 及其相关方法可以正确处理路径。

    文件可能正在实际被创建(即,您可能根本没有收到任何错误)。我的猜测是该文件是在“~/Desktopfile.txt”之类的地方创建的,因为您使用 -stringByAppendingString: 不会将字符串视为斜杠分隔的路径。检查你的主文件夹 - 我敢打赌文件在那里。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-27
      • 2021-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多