Reading and Writing Text Files in iPhone OS 3.0

by mattjdrake on June 24, 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.

//Method writes a string to a text file
-(void) writeToTextFile{
     	//get the documents directory:
     	NSArray *paths = NSSearchPathForDirectoriesInDomains
          	(NSDocumentDirectory, NSUserDomainMask, YES);
     	NSString *documentsDirectory = [paths objectAtIndex:0];

     	//make a file name to write the data to using the documents directory:
     	NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
                          							  documentsDirectory];
     	//create content - four lines of text
     	NSString *content = @"One\nTwo\nThree\nFour\nFive";
     	//save content to the documents directory
     	[content writeToFile:fileName 
               			 atomically:NO 
                 			   encoding:NSStringEncodingConversionAllowLossy 
                    				  error:nil];

}

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.

//Method retrieves content from documents directory and
//displays it in an alert
-(void) displayContent{
     	//get the documents directory:
     	NSArray *paths = NSSearchPathForDirectoriesInDomains
                     	(NSDocumentDirectory, NSUserDomainMask, YES);
     	NSString *documentsDirectory = [paths objectAtIndex:0];

     	//make a file name to write the data to using the documents directory:
     	NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
                          							  documentsDirectory];
     	NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
                                                      usedEncoding:nil
                                                             error:nil];
     	//use simple alert from my library (see previous post for details)
     	[ASFunctions alert:content];
     	[content release];

}

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.

Here Is How To Fast Track Your Objective-C Programming Skills…


Click here or the box to the right to access to your online workshop now…

Each lesson comes packed with comprehensive video, source code and text. When appropriate I include hands-on exercises. Check out the list below to see what is specifically covered in each lesson:

Module 1 – Getting Started With iPhone App Development

- Lesson 1 – Overview of iPhone OS
- Lesson 2 – Introduction to Tools: XCode, Interface Builder & iPhone Simulator
- Lesson 3 – Your First App
- Lesson 4 – Super-Charge XCode

Module 2 – Learn How to Program in C

- Lesson 1 – What is Programming?
- Lesson 2 – C Programming Basics and Specifics
- Lesson 3 – Functions
- Lesson 4 – Variables and Arrays
- Lesson 5 – Program Flow
- Lesson 6 – Loops
- Lesson 7 – Complex Data with Struct
- Lesson 8 – Putting It All Together

Module 3 – Master Object Oriented Programming With Objective-C

- Lesson 1 – What is Object Oriented Programming?
- Lesson 2 – Objects
- Lesson 3 – More Strings, Lists and the For Each Loop
- Lesson 4 – Memory Management
- Lesson 5 – Designing Your Own Classes
- Lesson 6 – Extending Classes With Categories
- Lesson 7 – Protocols & Key-Value Coding

Module 4 – No-BS Cocoa-Touch With iPhone SDK

- Lesson 1 – Overview of Cocoa-Touch + Model-View-Controller
- Lesson 2 – Using Interface Builder (The View)
- Lesson 3 – Target-Action and the View in Code
- Lesson 4 – Delegation
- Lesson 5 – Super-Charging Your View With Interface Builder
- Lesson 6 – Model & App Architecture

Click here or the box to the right to access to your online workshop now

Please share this if you like it!
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • email
  • FriendFeed
  • LinkedIn
  • MySpace
  • Ping.fm
  • StumbleUpon
  • Suggest to Techmeme via Twitter
  • Technorati
  • Tumblr
  • Yahoo! Bookmarks

Comments on this entry are closed.

{ 1 trackback }

Previous post:

Next post: