将多个NSArrays添加到NSMutableDictionary,并按数组顺序添加相应的匹配项
我有两个数组说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" }, ... }
您无法使用单个NSDictionary
获得该结构 – 您需要NSArray
的NSDictionary
对象。
以下是如何做到这一点:
NSMutableArray *menuItemNameImage = [NSMutableArray array]; for (int i = 0 ; i != itemNames.count ; i++) { [menuItemNameImage addObject: @{ @"itemName" : itemNames[i] , @"itemImage" : itemImages[i] }]; }
你可以使用NSArray
。 每个字典都有两个条目: itemImage
和itemName
。
它会是这样的:
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"];