I have this code to read in a text file, with words separated by newlines. What I want to do is read all the words into an array and then pick all the six-letter words from that array.
I have this code below, but it seems to be generating an error from within the for loop.
Also, after reading in the text file, do I have to release it?
NSString* path = [[NSBundle mainBundle] pathForResource:@"newdict" ofType:@"txt"];
NSString* content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
NSArray* allLinedStrings = [content componentsSeparatedByCharactersInSet:
[NSCharacterSet newlineCharacterSet]];
int wordcount = [allLinedStrings count];
int i;
NSMutableArray* sixLetterWords;
for( i = 0 ; i < wordcount ; i++)
{
NSString* word = [allLinedStrings objectAtIndex: i];
if (StrLength(word) == 6)
[sixLetterWords addObject:word];
}
Better options than a for loop are fast enumeration:
and blocks-based enumeration with
enumerateObjectsUsingBlock::There is also the possibility to filter the array:
Note that this last option gives you an autoreleased array — if you want to keep it around, you must retain it. With any of these, you no longer have to worry about the array length or explicit indexing; it is handled for you by the array. Fast enumeration is also, as its name indicates, faster than a plain
forloop.The method that you used to read the text file into your string,
stringWithContentsOfFile:encoding:error:, is notneworalloc, nor does it begin withcopyormutableCopy; therefore, according to Cocoa memory management rules, you do not own it and do not have to release it. (And if you want it to stick around past the end of the current method, you will need to retain it.)