Alexander of Norway Alexander of Norway - 1 year ago 126
iOS Question

Reading from text file in objective-c

I have a textfile which consists of multiple words. They are all separated by new lines.

What Ive tried:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"txt"];

if (filePath) { // This does trigger, so the file is actually found.

NSArray *arr = [filePath componentsSeparatedByString:@"\n"];


What Ive also tried:

NSMutableArray * lines = [[NSMutableArray alloc] initWithArray:[filePath componentsSeparatedByString:@"\n"] copyItems: YES];

Neither of these seems to work as I only seem to get the filepath when I read out lines using NSLog. Can any of you help?

The lines array only seem to consist of one object, the string of the location of the textfile.

I want an array where each string is a string separated by a line in the textile.

Answer Source

First of all you need to get the file within your application bundle. That means, you must put it inside your application's 'Resources' folder.

Then you can read it like this:

NSString* path = [[NSBundle mainBundle] pathForResource:@"filename" 

Then loading the content into a NSString is even easier:

NSString* content = [NSString stringWithContentsOfFile:path

Then create the array:

NSArray *arr = [content componentsSeparatedByString:@"\n"]; //might also be @"\r" check both.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download