Andrew H
Andrew H

Reputation: 522

Reading strings from txt files into NSArrays in iOS

After much reading it seems that, really, the only way to read a number of lines from a text file into an NSArray is with this:

NSString *myfilePath = [[NSBundle mainBundle] pathForResource:@"poem" ofType:@"txt"];

NSString *linesFromFile = [[NSString alloc] initWithContentsOfFile:myfilePath encoding:NSUTF8StringEncoding error:nil];

myArrayOfLines = [NSArray alloc];
myArrayOfLines = [linesFromFile componentsSeparatedByString:@"\n"];

NSArrays have a method for initWithContentsOfFile but I have not seen any examples of how to use this. I have read some posts that state that the file must be a plist and not a generic txt file.

Is this really the case? Is there a way to read lines (terminated with \n) directly into an NSArray?

Upvotes: 4

Views: 1409

Answers (1)

NSZombie
NSZombie

Reputation: 1867

You have it right, except the line myArrayOfLines = [NSArray alloc]; which is useless. Don't bother with plist if you already have a good txt file. But for curiosity, here is a link which explains how it works with plist files : link

Also, if you don't use ARC, you'll have some leaks, but that's another question, and we don't have the whole code, so I might be wrong.

Upvotes: 3

Related Questions