views:

723

answers:

2

I have a file of words/phrases separated by newlines. I need to get the file and read each word/phrase into the array. I have this so far:

    NSFileHandle *wordsFile = [NSFileHandle fileHandleForReadingAtPath:[[NSBundle     mainBundle] pathForResource:@"WordList"
                                   ofType:nil]];
    NSData *words = [wordsFile readDataToEndOfFile];
    [wordsFile closeFile];
    [wordsFile release];

But I'm not sure if that's right, and if so, where to go from there.

Also, teabot's answer of

NSString componentsSeparatedByCharactersInSet: NSCharacterSet newlineCharacterSet

works great, but it's 10.5 only. How would this behavior be replicated for 10.4?

+6  A: 

Here is an approach that should work - I'll leave out an actual code example as the implementation should be fairly straightforward given following:

Construct an NSString from your file with:

NSString stringWithContentsOfFile:encoding:error

Split the string into an array of NSStrings using the following:

NSString componentsSeparatedByCharactersInSet:
NSCharacterSet newlineCharacterSet

You should end up with an NSArray of NSStrings with each string containing one of the lines in your file.

teabot
Don't forget to filter out empty strings caused by blank lines, including the one that UNIX editors (such as vi) will leave at the end of the file.
Peter Hosey
That works great, but those last two are 10.5 only- what would replace them if I want compatibility on 10.4?
Walker Argendeli
Good call re: 10.4.x - I would advise you to revise the question to reflect this.
teabot
+3  A: 

Just for completeness (and because I am bored) here's a complete example bassed on teabot's post:

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

    NSArray *array = [string componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
    NSLog(@"%@",array);
micmoo