How to read the contents of a text file into an NSString

Imagine we had a file called myfile.txt which is a standard text file. On each line we have a new item we’d like to read so that our app can do something with it. Here’s how we do that:

// get a reference to our file
NSString *myPath = [[NSBundle mainBundle]pathForResource:@"myfile" ofType:@"txt"];

// read the contents into a string
NSString *myFile = [[NSString alloc]initWithContentsOfFile:myPath encoding:NSUTF8StringEncoding error:nil];

// display our file
NSLog("Our file contains this: %@", myFile);

It is likely that instead of a long list of text we’d rather have each line in a separate string.
Thankfully there’s a method for this:

// split our string into an array
NSArray *mySplit = [myFile componentsSeparatedByString:@"\n"];

// display any one of them like this
NSLog(@"Third Position: %@", [mySplit objectAtIndex:2]);




Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.