Reputation: 522
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
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