Make NSArray out of each word in text file
So what I want to accomplish is to make a NSArray out of a txt file and each word would be an object in that array. Below is some code that doesn't work. No crashes but doesn't do anything.
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"badwords" ofType:@"txt"];
if (filePath) {
NSString *fileContents = [NSString stringWithContentsOfFile:@"badwords.txt" encoding:NSUTF8StringEncoding error:nil];
lines = [fileContents componentsSeparatedByString:@"\n"];
}开发者_JAVA技巧
lines is a NSArray.
Any reason why this shouldn't work? Each word is separated by a line break.
A good reason: [NSString stringWithContentsOfFile: ...]
should be taking the filePath
you derived in the preceding statement as an argument and not @"badwords.txt"
, the literal string filename. That's the whole reason for deriving the filePath
in the first line -- you then want to use it in the second.
In other words I'm simply saying you should change this:
NSString *fileContents = [NSString stringWithContentsOfFile:@"badwords.txt" encoding:NSUTF8StringEncoding error:nil];
to this:
NSString *fileContents = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
精彩评论