【问题标题】:I have trouble with order of dictionary's keys after init初始化后字典键的顺序有问题
【发布时间】:2013-09-17 06:03:54
【问题描述】:

我存储了实体“SchedulesItems”。 当我尝试这个存储的分组结果时,我在键的顺序上遇到了问题。 例如:

NSMutableArray  *keysForDictionary  =   [[NSMutableArray alloc] init];
NSMutableArray  *objectsForDictionary   =   [[NSMutableArray alloc] init];

NSUInteger  index   =   0;

for ( EBResponseEventsSchedulesItem *schedulesItem in items ) {

    NSDate  *date   =   schedulesItem.date;

    if ( ![keysForDictionary containsObject:date] ) {
        [keysForDictionary addObject:date];
        [objectsForDictionary addObject:[NSMutableArray array]];
    }

    index   =   [keysForDictionary indexOfObject:date];

    [[objectsForDictionary objectAtIndex:index] addObject:schedulesItem];

}

// in this line array 'keysForDictionary' have right order, just like:
// 25.09.2013
// 26.09.2013
// 27.09.2013
// 28.09.2013

NSDictionary    *returnDictionary   =   [[NSDictionary alloc] initWithObjects: objectsForDictionary forKeys:keysForDictionary];

// but this line array [returnDictionary allKeys] have wrong order, just like:
// 25.09.2013
// 28.09.2013
// 27.09.2013
// 26.09.2013
// but objects which associated with this keys is ok

为什么字典的排序顺序被破坏了?

附言对不起我的英语 - 我来自俄罗斯

【问题讨论】:

    标签: ios sorting dictionary


    【解决方案1】:

    字典不是一个数组,其对象可以通过索引访问并因此具有顺序。 在字典中,对象及其键不以任何特定顺序存储。字典中的对象只能通过它们的键来访问。

    【讨论】:

    • 我知道。但我没有猜到尝试将'sortedArrayUsingSelector'用于[returnDictionary allKeys]。谢谢))
    【解决方案2】:

    因为方法allKeys 没有排序。来自文档:

    allKeys 返回一个包含字典键的新数组。

    • (NSArray *)allKeys 返回值 包含字典键的新数组,如果字典没有条目,则为空数组。

    讨论数组中元素的顺序没有定义。

    ps。如果将这两行结合起来会快得多:

    index   =   [keysForDictionary indexOfObject:date];
    [[objectsForDictionary objectAtIndex:index] addObject:schedulesItem];
    

    进入:

    [[objectsForDictionary objectAtIndex:[keysForDictionary count]-1 addObject:schedulesItem];
    

    此外,如果日期不是唯一的,您的逻辑将失败,因为 IndexOfObject:date 如果有重复的日期,将在数组中返回错误的行。

    pps。你为什么要使用数组来构建返回字典?为什么不直接在遍历 items 数组时将元素添加到返回字典中?

    【讨论】:

    • 我的逻辑不会失败,因为我希望有几个 schedulesItems 与 1 个日期相关联
    【解决方案3】:

    正如其他人已经说过的,NSDictionary 没有按设计排序。 但是,您可以在 NSArray 中保留对字典的引用,或者在之后对键进行排序,例如:

    NSArray *sortedKeys = [[returnDictionary allKeys] sortedArrayUsingSelector:@selector(compare:)];

    【讨论】:

    • 对不起,我已经尝试过使用这种方法 - sortUsingSelector...它不起作用((
    • 哦,对不起-它的工作。我的意思是'sortedArrayUsingSelector'。非常感谢你!
    • 您对方法名称的看法是正确的。我将编辑我的答案以反映它。
    猜你喜欢
    • 1970-01-01
    • 2019-09-17
    • 1970-01-01
    • 2010-09-25
    • 2019-04-06
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多