The Foundation framework gives the developer a few easy ways to read from and write to files. In this chapter, you’ll try a few of them out.
First, let’s see how you would take the contents of an NSString and put it into a file. When you write a string to a file, you need to specify which string encoding you are using. A string encoding describes how each character is stored as an array of bytes. ASCII is a string encoding that defines the letter ‘A’ as being stored as 01000001. In UTF-16, the letter ‘A’ is stored as 0000000001000001.
The Foundation framework supports about 20 different string encodings. UTF can handle an incredible collection of writing systems. It comes in two flavors: UTF-16, which uses two or more bytes for every character, and UTF-8, which uses one byte for the first 128 ASCII characters and two or more for other characters. For most purposes, UTF-8 is a good fit.
Create a new project: a Foundation Command Line Tool called Stringz. In main(), use methods from the NSString class to create a string and write it to the filesystem:
#import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { @autoreleasepool { NSMutableString *str = [[NSMutableString alloc] init]; for (int i = 0; i < 10; i++) { [str appendString:@"Aaron is cool!n"]; } [str writeToFile:@"/tmp/cool.txt" atomically:YES encoding:NSUTF8StringEncoding error:NULL]; NSLog(@"done writing /tmp/cool.txt"); } return 0; }
This program will create a text file that you can read and edit in any text editor. The string /tmp/cool.txt is known as the file path. File paths can be absolute or relative: absolute paths start with a / that represents the top of the file system, whereas relative paths start at the working directory of the program. Relative paths do not start with a /. In Objective-C programming, you’ll find that we nearly always use absolute paths because we typically don’t know what the working directory of the program is.