2012-02-27 40 views
0

我已经得到了这些数据,我从XML Feed中获取并解析为NSDictionaries。数据结构如下:Objective-C for循环嵌套NSDictionaries

item = { 
    address =  { 
    text = "1 Union Street"; 
    }; 
    data =  { 
    text = "Hello."; 
    }; 
    event_date =  { 
    text = "2012-02-27"; 
    }; 
    event_type =  { 
    text = pubQuiz; 
    }; 
    latitude =  { 
    text = "57.144994"; 
    }; 
    longitude =  { 
    text = "-2.10143170000003"; 
    }; 
    name =  { 
    text = "Mobile Tester"; 
    }; 
    picture =  { 
    text = "public://pictures/event_default.png"; 
    }; 
    time =  { 
    text = "23.00"; 
    }; 
    vname =  { 
    text = Test; 
    }; 
} 
//More items 

每个子节,即地址,数据,event_date等都是NSDictonaries。

我想遍历整个集合,并获取每个部分内的“文本”,以创建具有这些属性的“项目”数组。我已经尝试过在Objective-C中使用for..in循环结构,但迄今还没有取得任何成功。有没有人有几个指针?我很高兴通读任何有关如何遍历嵌套NSDictionaries的优秀教程或示例。

编辑:

好了的话,解析XML后,我得到的结构在那里。我想这样做的是遍历“项目”结构提取所有内部字典的“文本”字段 - 这样的事情:

foreach(item in array of dictionaries) { 
    myItem.address = item.address.text; 
    myItem.data = item.data.text; 
    ... 
} 

等。我希望这可以让它更清楚一些。

因此,卡住的部分是我想要在遍历NSDictionaries时设置该项目的属性的位置。这是我到目前为止有:

for(NSDictionary *item in self.eventsArray) { 
    for (NSDictionary *key in [item allKeys]) { 
     NSLog(@"%@", key); 
     id value = [item objectForKey:key]; 
     if ([value isKindOfClass:[NSDictionary class]]) { 
      NSDictionary* newDict = (NSDictionary*)value; 
      for (NSString *subKey in [newDict allKeys]) { 
       NSLog(@"%@", [newDict objectForKey:subKey]); 
      } 
     } 
    } 
} 

,输出:

地址 1联盟街 数据 你好。 ...

我只是不知道如何选择我创建的对象中的适当属性来设置所需的属性,如果这有什么意义?

+0

重复? http://stackoverflow.com/questions/3320511/how-to-iterate-nested-dictionaries-in-objective-c-iphone-sdk – Almo 2012-02-27 19:15:46

+0

只是好奇,是这些词典的字典,因为它是可能的每个项目有东西除了文字? – Joe 2012-02-27 19:16:20

+0

你对你想要的输出的描述很模糊;你应该提供一个它看起来像什么的例子。 – yuji 2012-02-27 19:18:53

回答

0

为了让我做的项目以下内容:

id eventsArray = [[[[XMLReader dictionaryForXMLData:responseData error:&parseError] objectForKey:@"root"] objectForKey:@"events"] objectForKey:@"event"]; 
if([eventsArray isKindOfClass:[NSDictionary class]]) 
{ 
    //there's only one item in the XML, so there's only an NSDictionary created. 
    for(NSString *item in (NSDictionary*)eventsArray) 
    { 
     //check what each item is and deal with it accordingly 
    } 
} 
else 
{ 
    //There's more than one item in the XML, an array is created 
    for(NSDictionary *item in (NSArray*)eventsArray) 
    { 
     for (NSString *key in [item allKeys]) 
     { 
      //check what value key is and deal with it accordingly 
     } 
    } 
} 

而且允许我访问所有元素。

0

您可以创建一个名为从原来的一个项目新字典(这里称为字典):

NSMutableDictionary *items = [[NSMutableDictionary alloc] init]; 

for (NSDictionary *dict in dictionaries) 
{ 
    [items setValue:[dict objectForKey:@"text"] forKey:[dict description]]; 
} 

它会创建以下字典:

item = { 
address = "1 Union Street", 
data = "Hello.", 
.... 
}