如何使用Objective-C编写文本文件?

时间:2011-01-23 22:24:27

标签: objective-c file

在.NET中,可以使用以下命令将文件写入文件系统:

FileStream fs = File.Create(@"Filename");
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("Hello, World!");
// etc...
sw.Close();
fs.Close();

如何在Objective-C和Cocoa中实现相同的操作?我相信它涉及NSMutableData类,但我不知道如何实现它。

6 个答案:

答案 0 :(得分:2)

Tiny Mac Tutorials有a post on this.

该帖子的示例代码如下:

// filetest.m
// Created by macateeny.blogspot.com Sept 2008.
// Copyleft (c) 2008. some rights reserved.
// 
// Compile from the command line with:
// gcc filetest.m -Wall -o filetest -framework Foundation
//
#import <Foundation/Foundation.h>

// main entry point of our file test tool with the argument counter and vector
int main(int argc,char *argv[])
{
    // allocate a memory pool for our NSString Objects
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // declare NSString Obj pointer and initialise it
    NSString *str = @"Cooking with Objective-C\r\n";

    // declare NSString filename and alloc string value
    NSString *filenameStr = @"./filetest.txt";

    // NSObject which contains all the error information
    NSError *error;

    // write contents and check went ok
    if(![str writeToFile: filenameStr atomically: YES encoding:NSUTF8StringEncoding error:&error]) {
            NSLog(@"We have a problem %@\r\n",[error localizedFailureReason]);
    }

    // unleash the allocated pool smithers
    [pool release];

    // The app is terminated
    return 0;
}

答案 1 :(得分:1)

请注意,Objective C是标准C的纯超集。大多数常见的posix库调用(在stdio,stdlib等中)是可用和可用的,只要你不尝试使用它们来逃避应用程序的沙箱(写入系统目录等)

因此,fopen()和fprintf()也可以很好地将ASCII或UTF8文本和数据写入文件。您可以使用NSSearchPathForDirectoriesInDomains查找相应的目录名称,并使用各种NSString方便方法将NSStrings转换为UTF8。

答案 2 :(得分:0)

NSString *str = @"Wollah";
[str writeToFile:@"/Wollah.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];

虽然建议使用NSURL,但我总是这样做。

答案 3 :(得分:0)

请参阅Apple's development docs - Cocoa concepts,尤其是此Strings图书馆的Apple概述文档所有概念首先会让您了解所需的详细信息

答案 4 :(得分:0)

对于iOS或MacOS上最新版本的Cocoa,如果您不想检查错误,可以执行此操作,

NSString *str = @"Wollah";
[str writeToFile:@"Wollah.txt" atomically:YES encoding:NSUTF8StringEncoding error:NULL];

答案 5 :(得分:-1)

NSStringwriteToFile方法。