从plist过滤NSArray的数据

时间:2012-07-06 11:13:48

标签: iphone

我想按城市过滤数据并将其打印到表格区域中。 我有这样的代码。

NSMutableArray *key1=[NSMutableArray arrayWithCapacity:count];
NSMutableArray *city=[NSMutableArray arrayWithCapacity:count];
NSMutableArray *name= [NSMutableArray arrayWithCapacity:count];
for(id key in data) {
    [key1 addObject:key];
}
for (int i=0;i<[key1 count]; i++) {
    NSLog(@"key:%@",[key1 objectAtIndex:i]);
}
for (int i=0;i<[key1 count]; i++) {
    NSDictionary *email_key=[data objectForKey:[key1 objectAtIndex:i]];
    [city addObject:[email_key objectForKey:@"city"]]; 
    [name addObject:[email_key objectForKey:@"f_name"]];
}

我有一些来自plist的城市。

我的Plist的内容:

<key>bh@gmail.com</key>
<dict>
    <key>fnmae</key><string>hello</string>
    <key>city</key><string>DElhi</string>
</dict>
<dict>
    <key>fnmae</key><string>hi</string>
    <key>city</key><string>Bombay</string>
</dict>

1 个答案:

答案 0 :(得分:0)

首先获取所有独特城市的名称,如下所示:

NSMutableDictionary *cityBasedData=[[NSMutableDictionary alloc] init];
for(id key in data) {
    [key1 addObject:key];
}
for (int i=0;i<[key1 count]; i++) {
    NSDictionary *email_key=[data objectForKey:[key1 objectAtIndex:i]];
    if (![cityBasedData objectForKey:[email_key objectForKey:@"city"]]) {
     NSMutableArray *nameList = [[NSMutableArray alloc] init];
     [nameList addObject:[email_key objectForKey:@"f_name"]];
     [cityBasedData setValue:nameList forKey:[email_key objectForKey:@"city"]];
     [nameList release]; 
    }
    else
    {
      NSMutableArray *nameList = [cityBasedData objectForKey:[email_key objectForKey:@"city"]];
      [nameList addObject:[email_key objectForKey:@"f_name"]];
     [cityBasedData setValue:nameList forKey:[email_key objectForKey:@"city"]];
    }

}

获取此字典后,您可以遍历字典中的每个键并获取每个键的数组:

for(id key in cityBasedData)
{
   //get array as follows:
   NSArray *namelist = [cityBasedData objectForKey:key];
}