Write to files with this Objective-C example

Here is a quick example to get you started on Objective-C. You can compile it within Terminal using the command line. Source code zip file here.
The gcc compiler command is as follows:
gcc filetest.m -Wall -o filetest -framework Foundation


Once compiled execute it as follows ./filetest
This will then create a text file called filetest.txt which contains a text string.
No magic required.

Note the writeToFile method has change for OS X 10.5 it now includes data encoding and NSError.
Once you have this working you can experiment with writeToURL...enjoy


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




md5sum: 9463cf40d33f02093e72d80320ba92e4 filetest.zip


0 comments: