Objective-C 创建一个带有字符串的文本文件

标签 objective-c cocoa nsstring save

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

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

最佳答案

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

}

关于Objective-C 创建一个带有字符串的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1820204/

相关文章:

swift - 使用未解析的标识符 : kCGWindowImageDefault (and other Core Graphics constants)

ios - UITabBarController 中的 TableView 内容插入

iphone - NSMutableArray removeObjectAtIndex : throws invalid argument exception

iphone - Xcode 4.2 首选项 "Support Wirelessly Connected Devices"有什么作用?

objective-c - 检测全屏菜单栏移动

ios - 删除 'NSString' 中的后端字符

python - 程序导致 OSX (Snow Leopard 10.6.4) 窗口服务器自发崩溃

macos - 根据 contentView 的新大小调整 NSWindow 的大小

ios - Xcode Beta 6 上的 NSString 和 String

ios - 在Swift或Objective-C中从字符串中删除确切的词组