Reading file to array

I have a file of words / phrases separated by newlines. I need to get a file and read every word / phrase in an array. I still have this:

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

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

Also answer teabot

NSStringSeparatedByCharactersInSet Elements: NSCharacterSet newlineCharacterSet

works great, but only 10.5. How will this behavior be replicated for 10.4?

+6
arrays file objective-c cocoa
source share
2 answers

Here is an approach that should work - I will not give an actual code example, since the implementation should be quite simple if:

Create an NSString from your file with:

 NSString stringWithContentsOfFile:encoding:error 

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

 NSString componentsSeparatedByCharactersInSet: NSCharacterSet newlineCharacterSet 

You should get an NSArray from NSStrings with each line containing one of the lines in your file.

+11
source share

Just for completeness (and because I'm bored) here is a complete example, bassed on teabot post:

  NSString *string = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"file" ofType:@"txt"]]; NSArray *array = [string componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]; NSLog(@"%@",array); 
+11
source share

All Articles