开发者

How can text files be written using Objective-C?

开发者 https://www.devze.com 2023-02-06 20:44 出处:网络
In .NET, a file can be written to the file system using: FileStream fs = File.Create(@\"Filename\"); StreamWriter sw = new StreamWriter(fs);

In .NET, a file can be written to the file system using:

FileStream fs = File.Create(@"Filename");
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("Hello, World!");
// etc...
sw开发者_C百科.Close();
fs.Close();

How would I achieve the same operation in Objective-C and Cocoa? I believe it involves the NSMutableData class, but I do not know how to implement it.


Tiny Mac Tutorials has a post on this.

The example code from that post is below:

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


Note that Objective C is a pure superset of standard C . Most of the usual posix library calls (in stdio, stdlib, etc.) are available and usable, as long as you don't try to use them to escape the app's sandbox (write to system directories, etc.)

So fopen() and fprintf() will also work perfectly well for writing ASCII or UTF8 text and data to files. You can use NSSearchPathForDirectoriesInDomains to find the appropriate directory names, and use various NSString convenience methods to convert NSStrings to UTF8.


See Apple's development docs - Cocoa concepts especially for this re Strings The Apple overview documents of the librairead all the concepts first it will give you a idea of what details you need


For the latest version of Cocoa on iOS or MacOS you can do this if you don't want to check for an error,

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


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

Although using an NSURL is recommended, and I always do that.


NSString has a writeToFile method.

0

精彩评论

暂无评论...
验证码 换一张
取 消