我有一个很大的 NSDictionary
,我需要遍历它并创建单独的 NSArray
。以下是内容:
(
{
id = {
text = "";
};
sub = {
text = " , ";
};
text = "";
"thumb_url" = {
text = "";
};
title = {
text = "2010-2011";
};
type = {
text = "title";
};
},
{
id = {
text = "76773";
};
sub = {
text = "December 13, 2010";
};
text = "";
"thumb_url" = {
text = "http://www.puc.edu/__data/assets/image/0004/76774/varieties/thumb.jpg";
};
title = {
text = "College Days - Fall 2010";
};
type = {
text = "gallery";
};
},
{
id = {
text = "";
};
sub = {
text = "";
};
text = "";
"thumb_url" = {
text = "";
};
title = {
text = "2009-2010";
};
type = {
text = "title";
};
},
{
id = {
text = "76302";
};
sub = {
text = "December 3, 2010";
};
text = "";
"thumb_url" = {
text = "http://www.puc.edu/__data/assets/image/0019/76303/varieties/thumb.jpg";
};
title = {
text = "Christmas Colloquy";
};
type = {
text = "gallery";
};
}
)
每个部分都有一个类型键,我需要检查一下。当它找到 title
键时,我需要将它们添加到数组中。然后将使用 gallery
键的下一部分需要在它自己的数组中,直到它找到另一个 title
键。然后将 gallery
键放入自己的数组中。
我正在使用 UITableView
部分标题和内容。因此,上面的 NSDictionary
应该有一个 NSArray *titles;
数组,以及另外两个数组,每个数组都包含标题后面的画廊。
我尝试过使用 for
循环,但我似乎无法正确使用它。任何想法将不胜感激。
最佳答案
您的日志有些不清楚,但我猜您的 NSDictionary
的值为 NSDictionary
?如果是这样:
NSMutableArray *titles = [NSMutableArray array];
// etc.
for (id key in sourceDictionary) {
NSDictionary *subDictionary = [sourceDictionary objectForKey:key];
if ([subDictionary objectForKey:@"type"] == @"title")
[titles addObject:[subDictionary objectForKey:@"title"]];
// etc.
}
您的问题有点不清楚...但这是您正确循环遍历 NSDictionary
的方式。
编辑:
NSMutableDictionary *galleries = [NSMutableDictionary dictionary];
NSString *currentTitle;
for (id key in sourceDictionary) {
NSDictionary *subDictionary = [sourceDictionary objectForKey:key];
NSString *type = [subDictionary objectForKey:@"type"];
if (type == @"title") {
currentTitle = [subDictionary objectForKey:@"title"];
if ([galleries objectForKey:currentTitle] == nil)
[galleries setObject:[NSMutableArray array] forKey:currentTitle];
} else if (type == @"gallery" && currentTitle != nil)
[[galleries objectForKey:currentTitle] addObject:subDictionary];
}
在此循环之后,galleries
将包含 NSString
类型的键(带有标题的值),以及对应的 NSArray
类型的对象(具有库 NSDictionarys
的值)。希望这就是您想要的。
关于iphone - 循环遍历 NSDictionary 以创建单独的 NSArrays,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4707759/