Reading and Writing Text Files in iPhone OS 3.0

Matthew Campbell, June 24th, 2009

iStock_000007449744XSmall.jpgReading and writing text files are one of the most basic things you need to do in iPhone development. In iPhone OS 3.0 things have changed a little bit here and there with some methods being deprecated.

I just wrote two example methods that you can use to see how you can turn a NSString into a text file and reverse the process.

Write the Contents of your NSString to the Filesystem

All I needed to do is create a NSString that has five lines in it and then I used the writeToFile method to save the contents. This version of writeToFile is like others that I have wrote about but it has a few more parameters.

Read Something from the Filesystem and Display It

Of course, once you write something to the filesystem you will want to use it again in the future. Here is a method I wrote as an example of this operation.

Discussion

That is it – you can do similar things with content like images and almost anything else with the NSData class. There is also a method in NSString (check out the header files in XCode) which advertises similar functionality for URL so it would look like you can do the same thing with your webserver. I had no luck with this. It was trivial to read a text file from my server, but I could not write files using the methods there; I know this can be done, just not with this very simple approaches.