23
Writing Files with NSString and NSData

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.

Writing an NSString to a file

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:

#​i​m​p​o​r​t​ ​<​F​o​u​n​d​a​t​i​o​n​/​F​o​u​n​d​a​t​i​o​n​.​h​>​

i​n​t​ ​m​a​i​n​ ​(​i​n​t​ ​a​r​g​c​,​ ​c​o​n​s​t​ ​c​h​a​r​ ​*​ ​a​r​g​v​[​]​)​ ​ ​ ​ ​{​
 ​ ​ ​ ​@​a​u​t​o​r​e​l​e​a​s​e​p​o​o​l​ ​{​

 ​ ​ ​ ​ ​ ​ ​ ​N​S​M​u​t​a​b​l​e​S​t​r​i​n​g​ ​*​s​t​r​ ​=​ ​[​[​N​S​M​u​t​a​b​l​e​S​t​r​i​n​g​ ​a​l​l​o​c​]​ ​i​n​i​t​]​;​
 ​ ​ ​ ​ ​ ​ ​ ​f​o​r​ ​(​i​n​t​ ​i​ ​=​ ​0​;​ ​i​ ​<​ ​1​0​;​ ​i​+​+​)​ ​{​
 ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​[​s​t​r​ ​a​p​p​e​n​d​S​t​r​i​n​g​:​@​"​A​a​r​o​n​ ​i​s​ ​c​o​o​l​!​​n​"​]​;​
 ​ ​ ​ ​ ​ ​ ​ ​}​
 ​ ​ ​ ​ ​ ​ ​ ​[​s​t​r​ ​w​r​i​t​e​T​o​F​i​l​e​:​@​"​/​t​m​p​/​c​o​o​l​.​t​x​t​"​
 ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​a​t​o​m​i​c​a​l​l​y​:​Y​E​S​
 ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​e​n​c​o​d​i​n​g​:​N​S​U​T​F​8​S​t​r​i​n​g​E​n​c​o​d​i​n​g​
 ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​e​r​r​o​r​:​N​U​L​L​]​;​
 ​ ​ ​ ​ ​ ​ ​ ​N​S​L​o​g​(​@​"​d​o​n​e​ ​w​r​i​t​i​n​g​ ​/​t​m​p​/​c​o​o​l​.​t​x​t​"​)​;​

 ​ ​ ​ ​}​
 ​ ​ ​ ​r​e​t​u​r​n​ ​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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset