将数组排序到字典中

Mar*_*man 7 arrays sorting iphone nsdictionary ios

我有很多字符串的数组.我不想把它们排成字典,所以所有字符串都是从同一个字母开始进入一个数组然后数组成为一个键的值; 键将是其值的数组中的所有单词开始的字母.

Key = "A" >> Value = "array = apple, animal, alphabet, abc ..."
Key = "B" >> Value = "array = bat, ball, banana ..."
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?非常感谢提前!

omz*_*omz 16

NSArray *list = [NSArray arrayWithObjects:@"apple, animal, bat, ball", nil];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString *word in list) {
    NSString *firstLetter = [[word substringToIndex:1] uppercaseString];
    NSMutableArray *letterList = [dict objectForKey:firstLetter];
    if (!letterList) {
        letterList = [NSMutableArray array];
        [dict setObject:letterList forKey:firstLetter];
    }
    [letterList addObject:word];
}
NSLog(@"%@", dict);
Run Code Online (Sandbox Code Playgroud)