NSDictionary按字母顺序排序

时间:2016-03-11 07:13:26

标签: ios objective-c iphone nsdictionary

我将NSDictionary作为参数传递给我的函数。我希望它的关键和值在插入时按顺序排列。 例如。预期产出是:

 mutable dict:{
            zKey1 = Value1;
            fKey2 = Value2;
            aKey3 = Value3;
        } 

我尝试过以下方法来创建和设置键值。

    NSMutableDictionary *mutableDict = [[NSMutableDictionary alloc]init];
        [mutableDict setObject:@"Value1" forKey:@"zKey1"];
        [mutableDict setObject:@"Value2" forKey:@"fKey2"];
        [mutableDict setObject:@"Value3" forKey:@"aKey3"];

    NSMutableDictionary *dic2=[[NSMutableDictionary alloc]initWithObjectsAndKeys:@"1004",@"userId",@"cucumber",@"domain",@"168d5c02f ",@"token",@"1004",@"userId1",@"cucumber",@"domain1",@"168d5c02f ",@"token1", nil];


    NSDictionary * dict = [NSDictionary
                               dictionaryWithObjects:@[@"Ravi",@"33",@"India",@"India"]
                               forKeys:@[@"name",@"age",@"location",@"country"]];
        NSArray *sortedKeys = [[dict allKeys] sortedArrayUsingSelector: @selector(compare:)];

        NSMutableArray *sortedValues = [NSMutableArray array];
        for (NSString *key in sortedKeys) {
            [sortedValues addObject: [dict objectForKey: key]];
        }

    NSString *obj1=@"1004";
        NSString *obj2=@"cucumber";
        NSString *obj3=@"168d5c02f";

        NSString *key1=@" userId";
        NSString *key2=@"domain";
        NSString *key3=@"token";
        NSLog(@"dict %@",dict);

        NSDictionary *dict8 =[NSDictionary
                              dictionaryWithObjects:@[obj1,obj2,obj3]
                              forKeys:@[key1,key2,key3]];

但没有任何效果我总是得到输出

    mutable dict:{
        aKey3 = Value3;
        fKey2 = Value2;
        zKey1 = Value1;
    } 


    dict8 {
        domain = cucumber;
        token = 168d5c02f;
        userId = 1004;
    }

     dict {
        age = 33;
        country = India;
        location = India;
        name = Ravi;
    }

    dic= {
        domain = cucumber;
        domain1 = cucumber;
        token = "168d5c02f ";
        token1 = "168d5c02f ";
        userId = 1004;
        userId1 = 1004;
    }

始终根据键的字母顺序对值进行排序。很多人说NSDictionary是一个未分类的容器。但确实有问题。绝望地需要帮助。提前谢谢。

1 个答案:

答案 0 :(得分:3)

默认情况下,

NSDictionary 未订购。它总是没有任何订单。要创建有序字典,您需要覆盖现有的数据结构形式。您可以阅读This tutorial以实现目标。

总结教程(因为每个人都讨厌只有链接的答案,链接可能随时死亡):

NSDictionary将其密钥存储在哈希表中,该表在设计上是无序的。由于缺少顺序是哈希表存储的基础,因此必须执行NSMutableDictionary的子类化(从而重新实现存储)。

在你的.h文件中

//
//  OrderedDictionary.h
//  OrderedDictionary
//
//  Created by Matt Gallagher on 19/12/08.
//  Copyright 2008 Matt Gallagher. All rights reserved.
//
//  Permission is given to use this source code file without charge in any
//  project, commercial or otherwise, entirely at your risk, with the condition
//  that any redistribution (in part or whole) of source code must retain
//  this copyright and permission notice. Attribution in compiled projects is
//  appreciated but not required.
//

#import <Cocoa/Cocoa.h>

@interface OrderedDictionary : NSMutableDictionary
{
    NSMutableDictionary *dictionary;
    NSMutableArray *array;
}

- (void)insertObject:(id)anObject forKey:(id)aKey atIndex:(NSUInteger)anIndex;
- (id)keyAtIndex:(NSUInteger)anIndex;
- (NSEnumerator *)reverseKeyEnumerator;

@end

在您的.m文件中:

//
//  OrderedDictionary.m
//  OrderedDictionary
//
//  Created by Matt Gallagher on 19/12/08.
//  Copyright 2008 Matt Gallagher. All rights reserved.
//
//  Permission is given to use this source code file without charge in any
//  project, commercial or otherwise, entirely at your risk, with the condition
//  that any redistribution (in part or whole) of source code must retain
//  this copyright and permission notice. Attribution in compiled projects is
//  appreciated but not required.
//

#import "OrderedDictionary.h"

NSString *DescriptionForObject(NSObject *object, id locale, NSUInteger indent)
{
    NSString *objectString;
    if ([object isKindOfClass:[NSString class]])
    {
        objectString = (NSString *)[[object retain] autorelease];
    }
    else if ([object respondsToSelector:@selector(descriptionWithLocale:indent:)])
    {
        objectString = [(NSDictionary *)object descriptionWithLocale:locale indent:indent];
    }
    else if ([object respondsToSelector:@selector(descriptionWithLocale:)])
    {
        objectString = [(NSSet *)object descriptionWithLocale:locale];
    }
    else
    {
        objectString = [object description];
    }
    return objectString;
}

@implementation OrderedDictionary

- (id)init
{
    return [self initWithCapacity:0];
}

- (id)initWithCapacity:(NSUInteger)capacity
{
    self = [super init];
    if (self != nil)
    {
        dictionary = [[NSMutableDictionary alloc] initWithCapacity:capacity];
        array = [[NSMutableArray alloc] initWithCapacity:capacity];
    }
    return self;
}

- (void)dealloc
{
    //This method is pre-ARC. Manual Release commands don't work now. 
    //[dictionary release]; 
    //[array release];
    //[super dealloc];
}

- (id)copy
{
    return [self mutableCopy];
}

- (void)setObject:(id)anObject forKey:(id)aKey
{
    if (![dictionary objectForKey:aKey])
    {
        [array addObject:aKey];
    }
    [dictionary setObject:anObject forKey:aKey];
}

- (void)removeObjectForKey:(id)aKey
{
    [dictionary removeObjectForKey:aKey];
    [array removeObject:aKey];
}

- (NSUInteger)count
{
    return [dictionary count];
}

- (id)objectForKey:(id)aKey
{
    return [dictionary objectForKey:aKey];
}

- (NSEnumerator *)keyEnumerator
{
    return [array objectEnumerator];
}

- (NSEnumerator *)reverseKeyEnumerator
{
    return [array reverseObjectEnumerator];
}

- (void)insertObject:(id)anObject forKey:(id)aKey atIndex:(NSUInteger)anIndex
{
    if (![dictionary objectForKey:aKey])
    {
        [self removeObjectForKey:aKey];
    }
    [array insertObject:aKey atIndex:anIndex];
    [dictionary setObject:anObject forKey:aKey];
}

- (id)keyAtIndex:(NSUInteger)anIndex
{
    return [array objectAtIndex:anIndex];
}

- (NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level
{
    NSMutableString *indentString = [NSMutableString string];
    NSUInteger i, count = level;
    for (i = 0; i < count; i++)
    {
        [indentString appendFormat:@"    "];
    }

    NSMutableString *description = [NSMutableString string];
    [description appendFormat:@"%@{\n", indentString];
    for (NSObject *key in self)
    {
        [description appendFormat:@"%@    %@ = %@;\n",
            indentString,
            DescriptionForObject(key, locale, level),
            DescriptionForObject([self objectForKey:key], locale, level)];
    }
    [description appendFormat:@"%@}\n", indentString];
    return description;
}

@end

您可以下载Matt Gallagher's orderedDictionary here