0

我在从 IOS 的属性列表中排序键时遇到困难。

我正在将列表加载到字典中,并从中提取键到数组中,使用方法对它们进行排序:“sortedArrayUsingSelector'selector(compare:)”

当我尝试使用这些键时,这些值似乎没有按照附加到那里的键进行排序?示例:(键值)未排序:Assens 0、Odense 1、Nyborg 1、Middelfart 0。已排序:Assens、1、Odense 1、Nyborg 0、Middelfart 0。

`

NSBundle *bundle = [NSBundle mainBundle];
    NSURL *KSplistURL = [bundle URLForResource:@"KommunerStedtillæg" 
                               withExtension:@"plist"];
    NSDictionary *dictionary = [NSDictionary 
                                dictionaryWithContentsOfURL:KSplistURL];
    self.kommuner = dictionary;

    //NSArray *keys = [[self.kommuner allKeys] sortedArrayUsingSelector:@selector(compare)];

    NSArray *components = [self.kommuner allKeys];
    NSArray *keys = [components sortedArrayUsingSelector:@selector(compare:)];


    NSMutableDictionary *newDict = [NSMutableDictionary dictionary];
    for (id key in keys)[newDict setObject:[dictionary objectForKey:key]forKey:key];




    self.kommunerKeys = [newDict allKeys];
    self.kommunerValues = [newDict allValues];

`

4

1 回答 1

2

为什么您认为字典会知道您正在对其键数组的不相关副本进行排序这一事实?您必须像这样创建另一个字典:

NSArray *keys = [[originalDict allKeys] sortedArrayUsingSelector:@selector(compare:)];
NSMutableDictionary *newDict = [NSMutableDictionary dictionary];
for (id key in keys)
    [newDict setObject:[originalDict objectForKey:key] forKey:key];

现在newDict包含排序的键值。

于 2012-07-02T06:39:15.193 回答