【问题标题】:Sort [NSDictionary allKeys] alphabetically按字母顺序排序 [NSDictionary allKeys]
【发布时间】:2013-09-29 07:53:42
【问题描述】:

我正在使用最新的 SDK 开发 iOS 5.0+ 应用程序。

我想显示一个带有国家/地区列表的UIPickerView。这些国家将按字母顺序排序。当用户选择一个国家时,我必须存储它的 ISO 代码。

这是我现在用来本地化国家名称的代码:

+ (NSArray*)countriesNames
{
    NSLocale *locale = [NSLocale currentLocale];
    NSArray *countryArray = [NSLocale ISOCountryCodes];

    NSMutableArray *sortedCountryArray = [[NSMutableArray alloc] init];

    for (NSString *countryCode in countryArray)
    {
        NSString* displayNameString = [locale displayNameForKey:NSLocaleCountryCode
                                                          value:countryCode];
        [sortedCountryArray addObject:displayNameString];
    }
    [sortedCountryArray sortUsingSelector:@selector(localizedCompare:)];

    return sortedCountryArray;
}

但是,我需要使用一些东西,例如,NSDictionary;让我知道获取 ISO 代码和本地化名称。

我尝试使用NSDictionary 而不是NSArray

+ (NSDictionary*)countriesNames
{
    NSLocale *locale = [NSLocale currentLocale];
    NSArray *countryArray = [NSLocale ISOCountryCodes];

    NSMutableDictionary* sortedCountryDic = [[NSMutableDictionary alloc] init];

    for (NSString *countryCode in countryArray)
    {
        NSString* displayNameString = [locale displayNameForKey:NSLocaleCountryCode
                                                          value:countryCode];
        [sortedCountryDic setObject:countryCode forKey:displayNameString];

    }

    [[sortedCountryDic allKeys] sortUsingSelector:@selector(localizedCompare:)];

    return sortedCountryDic;
}

但我得到一个编译时异常:No visible @interface for 'NSArray' declares the selector 'sortUsingSelector:'

这里:

[[sortedCountryDic allKeys] sortUsingSelector:@selector(localizedCompare:)];

如何对所有键进行排序?
有什么方法可以使用其 displayName 获取 ISOCode?​​strong>

【问题讨论】:

  • 为什么要使用国家名称而不是国家代码作为字典?
  • 它可能会发生,因为 -sortUsingSelector: 只是 NSMutableArray 类的方法。 NSArray 具有 -sortedArrayUsingSelector: 方法,而 allKeys 方法返回 NSArray 而不是 NSMutableArray 对象。

标签: ios objective-c sorting


【解决方案1】:

sortUsingSelector: 是 NSMutableArray 的方法而不是 NSArray 的方法 您可以使用 sortedArrayUsingSelector 对数组进行排序,您将得到一个包含已排序内容的新数组

- (NSArray *)sortedArrayUsingSelector:(SEL)comparator


+ (NSArray*)countriesNames
{
    NSLocale *locale = [NSLocale currentLocale];
    NSArray *countryArray = [NSLocale ISOCountryCodes];

    NSMutableDictionary* sortedCountryDic = [[NSMutableDictionary alloc] init];

    for (NSString *countryCode in countryArray)
    {
        NSString* displayNameString = [locale displayNameForKey:NSLocaleCountryCode
                                                          value:countryCode];
        [sortedCountryDic setObject:countryCode forKey:displayNameString];

    }

    return [[sortedCountryDic allKeys] sortedArrayUsingSelector:@selector(localizedCompare:)];    
}

【讨论】:

  • 这个方法返回一个NSArray,但是它的返回类型被声明为NSDictionary
猜你喜欢
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-08
  • 2011-01-30
相关资源
最近更新 更多