我从XML Feed中获取了这些数据,并将其解析为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后,我得到那个结构。我想要做的是遍历“item”结构以提取所有内部词典的“text”字段 - 如下所示:
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 :(得分:0)
您可以从原始字典创建一个名为items的新字典(此处称为字典):
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.",
....
}
答案 1 :(得分: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
}
}
}
这使我可以访问所有元素。