我有一个叫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];
}问题是,对于每个键,只设置了一个值,但我需要所有对象都有一个具有相同值的第一个字母。例如,价值=‘b’-> @“熊”,@“黑天鹅”,@“水牛”。
发布于 2015-04-20 11:34:00
试一试
for (NSString *str in animals) {
NSString *firstLetter = [str substringToIndex:1];
if(!myMutableDictionary[firstLetter])
{
myMutableDictionary[firstLetter] = [NSMutableArray new];
}
NSMutableArray *arr = myMutableDictionary[firstLetter];
[arr addObject:str];
}发布于 2015-04-20 11:38:50
以下是满足您需求的代码。
步骤1:分配NSMutableDictionary。
步骤2:在解析NSArray时,检查dictionary中是否有可用的键。如果可用,则该数组来自相同的键,并在array中添加新元素,并在dictionary中更新same key。如果不可用,则在new key中创建dictionary。这是密码。
NSMutableDictionary* dictTemp = [[NSMutableDictionary alloc]init];
for (NSString *str in animals) {
NSString *firstLetter = [str substringToIndex:1];
if([[dictTemp allKeys] containsObject:firstLetter]){
NSMutableArray* arrayInner = [NSMutableArray arrayWithArray:[dictTemp valueForKey:firstLetter]];
[arrayInner addObject:str];
[dictTemp setValue:arrayInner forKey:firstLetter];
}
else{
NSMutableArray* arrayInner = [[NSMutableArray alloc] init];
[arrayInner addObject:str];
[dictTemp setValue:arrayInner forKey:firstLetter];
}
}
NSLog(@"Output : %@",dictTemp);https://stackoverflow.com/questions/29746547
复制相似问题