2012-02-27 41 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.", 
.... 
}