ios - NSMutableDictionary setValue :/forKey:?

标签 ios objective-c iphone

<分区>

我有一个名为 animals 的 NSMutableArray。我需要创建一个 NSMutableDictionary,以便动物数组中的所有名称都具有以特定首字母 = Values 开头的 Keys

这是动物数组:

NSMutableArray *animals = [NSMutableArray arrayWithObjects:@"Bear", @"Black Swan", @"Buffalo", @"Camel", @"Cockatoo", @"Dog", @"Donkey", @"Emu", @"Giraffe", @"Greater Rhea", @"Hippopotamus", @"Horse", @"Koala", @"Lion", @"Llama", @"Manatus", @"Meerkat", @"Panda", @"Peacock", @"Pig", @"Platypus", @"Polar Bear", @"Rhinoceros", @"Seagull", @"Tasmania Devil", @"Whale", @"Whale Shark", @"Wombat", nil];

这是我将其设置为 MutableDictionary 的代码:

 for(NSString *str in animals) {
     NSString *firstLetter = [str substringToIndex:1];
     NSArray *newArr = [NSArray arrayWithObject:str];
     [myMutableDictionary setValue:newArr forKey:firstLetter];
 }

问题是每个键只设置了一个值,但我需要所有对象的第一个字母具有相同的值。例如。 value='b' -> @"Bear", @"Black Swan", @"Buffalo".

最佳答案

尝试

for (NSString *str in animals) {
    NSString *firstLetter = [str substringToIndex:1];
    if(!myMutableDictionary[firstLetter])
    {
        myMutableDictionary[firstLetter] = [NSMutableArray new];
    }
    NSMutableArray *arr = myMutableDictionary[firstLetter];
    [arr addObject:str];
}

关于ios - NSMutableDictionary setValue :/forKey:?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29746547/

相关文章:

iphone - UIAlertViewDelegate clickedButtonAtIndex : usefulness?

iphone - 使用 IB 将分段控件添加到导航栏

ios - queueReusableCellWithReuseIdentifier 在 Xcode 中做什么?

Objective-C 整洁

iphone - 使用 UITableView ScrollPosition Middle :atScrollPosition: causes my tableview to become unscrollable 时出错

ios - 如何在 iOS 中向包含图像 (nsdata) 的 URL 发出 PUT 请求

javascript - 追加 UIWebView

iphone - iOS4中文本的阴影效果

android - 动态更改 iOS 和 Android 上的应用程序图标

ios - iOS:无法获取XMPP聊天的脱机消息