我试图从文件中读取的文字如下:" DREAM_TITLE:blah blah blah"。我遇到的问题是for循环(特别是containsString方法),它一直告诉我DREAM_TITLE键不在那里,当它明显存在并且它甚至被加载到初始数组中时。请哈尔!非常菜鸟,对不起,如果有人冒犯了。谢谢!
-(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;
答案 0 :(得分:0)
当原始数组足够时,你已经创建了一个数组数组:
NSArray *numberOfLines = [[NSArray alloc] initWithObjects:[fileContent componentsSeparatedByString:@"\n"], nil];
这可以简单地说:
NSArray *lines = [fileContent componentsSeparatedByString:@"\n"];
接下来,要搜索数组中的每一行,只需使用[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"];
}
}
虽然这不是特别准确,因为您只应在key
之前在文本中搜索:
...