1

是否有可能按名称检查数组中的对象。在我的应用程序的某个时刻,我需要访问 plist 并提取存储在我通过其名称找到的对象下的信息。我需要这样做的原因是因为我没有在我的数组中放置对象的整数。

我已经开始了通常的程序,但我没有得到任何地方。也许对我来说有点太晚了......

这就是我的 plist 的样子

Array
 Dictionary
      title ...
      text ...
      ect ...
 Dictionary
      title ...
      text ...
      ect ...
  Dictionary
      title ...
      text ...
      ect ...

到目前为止,我的代码根本没有帮助。我肯定做错了什么。

-(NSString*)nameFromPlist:(NSString*)name {

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"Orte.plist"];
_regionArray = [NSArray arrayWithContentsOfFile:writableDBPath];

NSString *string = [[NSString alloc]init];

for(NSDictionary *dict in _regionArray) {
    string = [[dict objectForKey:name] valueForKey:@"title"];

}

return [NSString stringWithFormat:@"%@",string];

}

我的字符串只是返回空值。

有什么想法吗?非常感谢!

回答:

这是每个人的代码:

-(NSString*)nameFromPlist:(NSString*)name {

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *tmpFileName = [[NSString alloc] initWithFormat:@"Orte.plist"];
NSString *path = [documentsDirectory stringByAppendingPathComponent:tmpFileName];

NSString *string;
NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:path];

NSDictionary *dict = [[NSDictionary alloc] init];
NSString *title;
for (int i=0; i<[array count]; i++) {
    dict = [array objectAtIndex:i];
    title = [dict valueForKey:@"title"];

    if([title isEqualToString:name]) {
        string = [dict valueForKey:@"title"];
        NSLog(@"Titel: %@", string);
    }        
}

return [NSString stringWithFormat:@"%@",string];

}

非常感谢大家!

4

2 回答 2

0

First you don't need to alloc the NSString, 'cause you'll get a different one from valueForKey.

Then if I understood right what you want to get a better code may be something that make use of NSPredicate or the block-based indexOfObjectPassingTest. Both iterate across the array and perform a test on the elements to get you the matching elements (or the index of them).

于 2012-11-27T12:37:44.687 回答
0
NSString* plistPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"<PlistFileName>" ofType:@"plist"];
NSArray *array = [[NSArray alloc] initWithContentsOfFile:plistPath];
NSMutableArray* titles = [[NSMutableArray alloc] init];
for (NSDictionary* d in array)
    [titles addObject:[d objectForKey:@"title"]];
NSLog(@"Object found at index %i", [a indexOfObject:@"<Your object name>"]);

确保您正在针对 NSNotFound 进行测试以查找失败,而不是(比如说)0。

于 2012-11-27T13:06:24.147 回答