复制具有多个子词典的字典,并仅从子词典中返回某些键

时间:2009-08-19 17:16:21

标签: iphone arrays dictionary copy

在我目前的iPhone项目中,我创建了一个字典,用“名称”键的第一个字母对子字典进行分组。 NSLog返回以下内容。我想创建一个相同的字典,只显示每个首字母键下的“名称”键。复制子词典中某些项目的最佳方法是什么? ObjectForKey方法将仅选择首字母的项目(例如:“B”或“C”)。如果我没有清楚地解释清楚,请告诉我。 谢谢!

sectionedDictionaryByFirstLetter:{
B =     (
            {
        Name = "B...A Name Starting with B";
        Image = "ImageName1.png";
        Text = "Some Text";
     }
 );
C =     (
            {
        Name = "C...A Name Starting with C";
        Image = "ImageName2.png";
        Text = "Some Text";
     }
 );
N =     (
            {
        Name = "N...A Name Starting with N";
        Image = "ImageName3.png";
        Text = "Some Text";

     },
            {
        Name = "N...A Name Starting with N";
        Image = "ImageName4.png";
        Text = "Some Text";

     },
            {
        Name = "N...A Name Starting with N";
        Image = "ImageName5.png";
        Text = "Some Text";

     }
   );
}

我正在寻找的最终结果是:

sectionedDictionaryByFirstLetter:{
B =     (
            {
        Name = "B...A Name Starting with B";
     }
 );
C =     (
            {
        Name = "C...A Name Starting with C";
     }
 );
N =     (
            {
        Name = "N...A Name Starting with N";
     },
            {
        Name = "N...A Name Starting with N";
     },
            {
        Name = "N...A Name Starting with N";
     }
   );
}

2 个答案:

答案 0 :(得分:2)

Core Foundation有一个很棒的功能,CFDictionaryApplyFunction(我希望他们也将功能移植到NSDictionary)。但是,NSDictionaryCFDictionary是“免费桥接”,这意味着您可以免费在它们之间进行投射。

因此,解决方案是创建一个应用程序函数SaveName,该函数将在上面的CFDictionaryApplyFunction中使用。例如:

void SaveName(const void* key, const void* value, void* context) {
  NSMutableDictionary* result = (NSMutableDictionary*) context;
  NSDictionary* dataDict = (NSDictionary*) value;
  NSString* letterKey = (NSString*) key;
  [result setObject:[dataDict valueForKey:@"Name"] forKey:@letterKey];
}

void main() {

   NSDictionary* exampleDict = .. ;
   NSMutableDictionary* resultDict = [NSMutableDictionary dictionary];
   CFDictionaryApplyFunction((CFDictionaryRef)exampleDict, SaveName, (void*)resultDict);
   // now, the resultDict contains key-value pairs of letter-name!
}

我的代码假定“value”字典中只有一个对象。您可以更改SaveName以考虑自己的数据结构,但这基本上就是这样做的。

答案 1 :(得分:1)

NSMutableDictionary* newDict = [NSMutableDictionary dictionary];
for (NSString* key in sectionedDictionaryByFirstLetter) {
    NSMutableArray* newList = [NSMutableArray array];
    [newDict setObject:newList forKey:key];
    for (NSDictionary* entry in [sectionedDictionaryByFirstLetter objectForKey:key]) {
        NSString* name = [entry objectForKey:@"Name"];
        [newList addObject:[NSDictionray dictionaryWithObject:name forKey:@"Name"]];
    }
}