使用初始名称创建 NSDictionary 进行排序 [英] Creating NSDictionary with Initial Name to Sort

查看:51
本文介绍了使用初始名称创建 NSDictionary 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试合并来自此链接的代码在使用我自己的字典时进入我自己的应用程序.但是,我遇到了几个问题.

I'm trying to merge the code from this link into my own application while using my own dictionary. I have had several problems, however.

我的代码生成了这种字典(因为我使用 Web 服务从 MySQL 数据库中获取这些数据):

My code produces this kind of dictionary (because I'm using a web service to get this data from a MySQL database):

{audiences = ({
            name = ABDUL;
            id = 1;
        },{
            name = ELSA;
            id = 2;
        },...etc)}

不过,我想要一本这样的字典:

However, I want a dictionary like this:

audiences = @{@"B" : @[@"Bear", @"Black Swan", @"Buffalo"],
              @"C" : @[@"Camel", @"Cockatoo"],
              @"D" : @[@"Dog", @"Donkey"]};

就我而言,它看起来像这样:

Which, in my case, would appear like this:

audience = @{@"A":@[@"Abdul"],
             @"E":@[@"Elsa"]};

总结一下我的问题:1) 如何仅使用 names(无 id)创建 NSDictionary?2) 包含首字母的字典

To summarize my problems: 1) How can I create an NSDictionary using only the names (no id)? 2) The dictionary including initial in it

感谢您的帮助,我是 Xcode 和 Objective-C 的新手,所以如果我问的是菜鸟问题,请原谅我.另外,请容忍我的英语不好.提前致谢.

Thanks for your help, I'm a newbie in Xcode and Objective-C, so please forgive me if I'm asking a noob question. Also, please bear with my bad English. Thanks in advance.

推荐答案

因此,您从 Web 服务收到的初始数据结构是(在 Cocoa 中重新表达):

So, your initial data structure received from the web service is (re-expressed in Cocoa):

NSDictionary* data = @{ @"audiences" : @[
                                          @{ @"name" : @"ABDUL",
                                             @"id" : @1 },
                                          @{ @"name" : @"ELSA",
                                             @"id" : @2 },
                                        ] };

您可以像这样构建您描述的数据结构:

You can build the data structure you describe like this:

NSMutableDictionary* audience = [NSMutableDictionary dictionary];
for (NSDictionary* person in data[@"audiences"])
{
    NSString* name = person[@"name"];
    if (![name length])
        continue;

    NSRange range = [name rangeOfComposedCharacterSequenceAtIndex:0];
    NSString* key = [[name substringWithRange:range] uppercaseString];
    NSMutableArray* list = audience[key];
    if (!list)
    {
        list = [NSMutableArray array];
        [audience setObject:list forKey:key];
    }
    [list addObject:name];
}

这篇关于使用初始名称创建 NSDictionary 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆