2009-11-30 85 views
11

我正在尝试使用字符串内容创建一个文本文件到我的桌面。我不知道我是否做得对,我没有得到错误,但它也不能工作...Objective-C使用字符串创建文本文件

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

回答

13

你不知道你是否因为你'忽略-writeToFile:...方法返回的YES/NO值,并且不给它记录任何可能的失败的错误指针。如果方法返回NO,那么您将检查(并处理或呈现)错误以查看错误。

根据猜测,失败是由于您构建的路径。尝试-stringByAppendingPathComponent:而不是-stringByAppendingString:...这和它的相关方法正确地处理路径。

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

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

} 
+0

完美的男人......谢谢。 – 2013-06-19 20:57:57

+0

这工作完美 – MayorMonty 2013-10-05 16:07:27

+0

谢谢,队友!简单易用。 – Felipe 2017-03-17 21:13:53

-3

问题是桌面目录字符串以无(no /)结尾。使用UIAlertview检查(在iPhone上)。

+1

什么? 1)如果你这样做,你不需要使用'/'。 2.)你在哪里看到一个UIAlertView?我不。 3)这个问题在2年前就被问到了。 – 2011-08-14 17:43:58

+0

..我们为什么要检查一下iOS上的“桌面”有什么用处? iOS没有这种东西。 – 2015-08-26 00:49:55