The text I'm trying to read from the file looks like this: "DREAM_TITLE: blah blah blah". The issue I'm running into is within the for loop (particularly the containsString method) which keeps telling me that the the key DREAM_TITLE is not there, when it clearly is there and it even gets loaded in the initial array. Please HALP! Very noob here, sorry if anyone's offended. Thanks!
-(NSMutableArray *)findValueForKey:(NSString *)key{
NSString *path = [[NSBundle mainBundle] pathForResource:@"sampleData"
ofType:@"txt"];
NSString *fileContent = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
NSMutableArray *arrayOfKeyValues = [[NSMutableArray alloc] init];
NSArray *numberOfLines = [[NSArray alloc] initWithObjects:[fileContent componentsSeparatedByString:@"\n"], nil];
for (int i=0; i<[numberOfLines count]; i++){
if ([[numberOfLines objectAtIndex:i] containsObject:key]){
NSArray *tempArray = [numberOfLines[i] componentsSeparatedByString:@":"];
[arrayOfKeyValues insertObject:[tempArray objectAtIndex:1] atIndex:i];
}
else {
[arrayOfKeyValues insertObject:@"no value for key found" atIndex:i];
}
}
return arrayOfKeyValues;
You have created an array of an array for some reason, when the original array would have sufficed:
NSArray *numberOfLines = [[NSArray alloc] initWithObjects:[fileContent componentsSeparatedByString:@"\n"], nil];
this can be simply:
NSArray *lines = [fileContent componentsSeparatedByString:@"\n"];
Next, to search each line in the array, simply use [NSString rangeOfString:]
:
for (NSUInteger i = 0; i < [lines count]; i++) {
if ([lines[i] rangeOfString:key].location != NSNotFound) {
NSArray *tempArray = [lines[i] componentsSeparatedByString:@":"];
[arrayOfKeyValues addObject:tempArray[1]];
} else {
[arrayOfKeyValues addObject:@"no value for key found"];
}
}
Although, this is not particularly accurate, as you should only be searching for key
in text before the :
...