将多个NSArrays添加到NSMutableDictionary,并按顺序排列相应的匹配项

时间:2013-08-29 02:34:26

标签: ios objective-c nsarray nsdictionary

我有两个数组,分别是itemName和itemImages

NSArray *itemName = @[@"Blog", @"Missions", @"Subscriptions", @"Questions", @"Aide",@"Disconnect"];
NSArray *itemImages = @[@"ico-1",@"ico-2", @"ico-3", @"ico-4", @"ico-5", @"ico-6"];

我需要将它们添加到词典

 NSMutableDictionary *menuItemNameImage = [[NSMutableDictionary alloc] init];
 [menuItemNameImage setValue:itemName forKey:@"itemName"];
 [menuItemNameImage setValue:itemImages forKey:@"itemImages"];

 NSLog(@"%@", menuItemNameImage);

但这会产生以下词典

{
    itemImages =     (
        "ico-1",
        "ico-2",
        "ico-3",
        "ico-4",
        "ico-5",
        "ico-6"
    );
    itemName =     (
        Blog,
        Missions,
        Subscriptions,
        Questions,
        Aide,
        Disconnect
    );
}

我更想要的是有人这样想:

{ 
  { 
    itemImages = "icon-1",
    itemName = Blog
  },
  { 
    itemImage = "icon-2",
    itemName = "Missions"
  }, ...
}

2 个答案:

答案 0 :(得分:2)

您无法使用单个NSDictionary获得该结构 - 您需要NSArrayNSDictionary个对象。

以下是如何做到这一点:

NSMutableArray *menuItemNameImage = [NSMutableArray array];
for (int i = 0 ; i != itemNames.count ; i++) {
    [menuItemNameImage addObject: @{
        @"itemName" : itemNames[i]
    ,   @"itemImage" : itemImages[i]
    }];
}

答案 1 :(得分:2)

您可以使用NSArray NSDictionaries。每个字典都有两个条目:itemImageitemName

这将是这样的:

NSArray *itemName = @[@"Blog", @"Missions", @"Subscriptions", @"Questions", @"Aide",@"Disconnect"];
NSArray *itemImages = @[@"ico-1",@"ico-2", @"ico-3", @"ico-4", @"ico-5", @"ico-6"];

NSMutableArray *menuItemNameImage = [NSMutableArray new];

for (NSInteger i = 0; i < itemName.count; i++) {
    NSMutableDictionary *itemNameImage = [NSMutableDictionary new];

    itemNameImage[@"itemName"] = itemName[i];

    //just a precaution if the array os images is smaller than the ones of names, to avoid unwanted crashes
    if (i < itemImages.count) { 
        itemNameImage[@"itemImage"] = itemImages[i];
    }

    [menuItemNameImage addObject:itemNameImage];
}

NSLog(@"%@", menuItemNameImage);

输出,如您所愿:

(
    {
        itemImage = "ico-1";
        itemName = Blog;
    },
    {
        itemImage = "ico-2";
        itemName = Missions;
    },
    {
        itemImage = "ico-3";
        itemName = Subscriptions;
    },
    {
        itemImage = "ico-4";
        itemName = Questions;
    },
    {
        itemImage = "ico-5";
        itemName = Aide;
    },
    {
        itemImage = "ico-6";
        itemName = Disconnect;
    }
)

您可以访问这样的元素,例如:

NSString *firstItemName = menuItemNameImage[0][@"itemName"]; 
NSString *firstItemImage = menuItemNameImage[0][@"itemImage"];