NSDictionary:将 NSString 键转换为小写以在其上搜索字符串

Posted

技术标签:

【中文标题】NSDictionary:将 NSString 键转换为小写以在其上搜索字符串【英文标题】:NSDictionary: convert NSString keys to lowercase to search a string on them 【发布时间】:2010-06-03 16:59:08 【问题描述】:

我正在开发一个 iPhone 应用程序。

我使用 NSDictionary 将城市名称作为键存储,将人口作为值存储。我想用小写字母搜索键。

我用过这个:

NSDictionary *dict;

[dict objectForKey:[[city stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] lowercaseString]];

但是,它不起作用。

我知道,我可以做一个 for,将键转换为小写并与城市进行比较。

还有其他方法吗?也许,使用 NSDictionary 方法。

更新 NSDictionary 是从属性列表中加载的。

谢谢。

【问题讨论】:

密钥的格式是否已知?即全部小写,没有空格?而且您的示例不起作用,因为您从未实例化字典。 如果你想使用小写键进行搜索,你不能只使用小写键将数据放入字典吗? @jshier:这只是一个例子。我没有复制所有代码。键是 NSString。它们是用户写下的城市名称。 @iPhone 初学者:我不想那样做。我想要像往常一样的城市名称(首字母大写)。 【参考方案1】:

我在 NSDictionary 类别中使用此方法。

@implementation NSDictionary (MyCategory)
- (NSDictionary *)dictionaryWithLowercaseKeys 
    NSMutableDictionary *result = [NSMutableDictionary dictionaryWithCapacity:0];
    NSString *key;

    for (key in self) 
        [result setObject:[self objectForKey:key] forKey:[key lowercaseString]];
    

    return result;

@end

【讨论】:

看在上帝的份上,你有当前字典的长度,因此最终字典... [NSMutableDictionary dictionaryWithCapacity:0] 与实际大小!!! (例如[NSMutableDictionary dictionaryWithCapacity:self.count])【参考方案2】:

虽然我仍然不清楚你想要什么,但这个循环搜索键不区分大小写。获取该键的值就很简单了。

for key in dict

    if ([key caseInsensitiveCompare: @"Whatever"] == NSOrderedSame)
        NSLog(@"They are equal.");

【讨论】:

如果您不希望找到很多密钥,请考虑在找到密钥后打破循环。【参考方案3】:

我会说创建第二个字典。从属性集加载后,遍历该字典并将对象插入第二个字典。随时将键转换为小写。然后释放第一本字典。

【讨论】:

【参考方案4】:

以上答案仅适用于没有任何嵌套的平面字典。我创建了一个类别,该类别创建现有 NSDictionary 的副本,其中每个键都转换为小写。

标题NSDictionary+LowercaseKeys.h

#import <Foundation/Foundation.h>

@interface NSDictionary (LowercaseKeys)

/*
 Recursive algorithm to find all nested dictionary keys and create an NSMutableDictionary copy with all keys converted to lowercase.
 Returns an NSMutableDictionary with all keys and nested keys converted to lowercase.
 */
+ (NSMutableDictionary *)dictionaryWithLowercaseKeysFromDictionary:(NSDictionary *)dictionary;

/*
 Convienience method to create a new lowercase dictionary object an existing NSDictionary instance
 Returns an NSMutableDictionary with all keys and nested keys converted to lowercase.
 */
- (NSMutableDictionary *)dictionaryWithLowercaseKeys;

@end

实现NSDictionary+LowercaseKeys.m

#import "NSDictionary+LowercaseKeys.h"

@implementation NSDictionary (LowercaseKeys)

/*
 Recursive algorithm to find all nested dictionary keys and create an NSMutableDictionary copy with all keys converted to lowercase
 Returns an NSMutableDictionary with all keys and nested keys converted to lowercase.
 */
+ (NSMutableDictionary *)dictionaryWithLowercaseKeysFromDictionary:(NSDictionary *)dictionary

    NSMutableDictionary *resultDict = [NSMutableDictionary dictionaryWithCapacity:[dictionary count]];
    [dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) 
        // There are 3 types of objects to consider, NSDictionary, NSArray and everything else
        id resultObj;
        if ([obj isKindOfClass:NSDictionary.class])
        
            // Recursively dig deeper into this nested dictionary
            resultObj = [NSMutableDictionary dictionaryWithLowercaseKeysFromDictionary:obj];
        
        else if ([obj isKindOfClass:NSArray.class])
        
            /*
             Iterate over this nested NSArray. Recursively convert any NSDictionary objects to the lowercase version.
             If the array contains another array then continue to recursively dig deeper.
            */
            resultObj = [NSMutableArray arrayWithCapacity:[obj count]];
            for (id arrayObj in obj)
            
                if ([arrayObj isKindOfClass:NSDictionary.class])
                    [resultObj addObject:[NSMutableDictionary dictionaryWithLowercaseKeysFromDictionary:arrayObj]];
                else if ([arrayObj isKindOfClass:NSArray.class])
                    [resultObj addObject:[NSMutableDictionary arrayWithLowercaseKeysForDictionaryArray:arrayObj]];
                else
                    [resultObj addObject:arrayObj];
            
        
        else
        
            // The object is not an NSDictionary or NSArray so keep the object as is
            resultObj = obj;
        

        // The result object has been converted and can be added to the dictionary. Note this object may be nested inside a larger dictionary.
        [resultDict setObject:resultObj forKey:[key lowercaseString]];
    ];
    return resultDict;


/*
 Convienience method to create a new dictionary object with all lowercase keys from an existing instance
 */
- (NSMutableDictionary *)dictionaryWithLowercaseKeys

    return [NSMutableDictionary dictionaryWithLowercaseKeysFromDictionary:self];


#pragma mark - Private helpers

/*
 Convert NSDictionary keys to lower case when embedded in an NSArray
 */
+ (NSMutableArray *)arrayWithLowercaseKeysForDictionaryArray:(NSArray *)dictionaryArray

    NSMutableArray *resultArray = [NSMutableArray arrayWithCapacity:[dictionaryArray count]];
    for (id eachObj in dictionaryArray)
    
        if ([eachObj isKindOfClass:NSDictionary.class])
            [resultArray addObject:[NSMutableDictionary dictionaryWithLowercaseKeysFromDictionary:eachObj]];
        else if ([eachObj isKindOfClass:NSArray.class])
            [resultArray addObject:[NSMutableDictionary arrayWithLowercaseKeysForDictionaryArray:eachObj]];
    
    return resultArray;


@end

【讨论】:

以上是关于NSDictionary:将 NSString 键转换为小写以在其上搜索字符串的主要内容,如果未能解决你的问题,请参考以下文章

如何从 NSDictionary 中获取键和值?

将 JSON 字符串转换为 NSDictionary 时,并非所有键都有效

从 NSArray 过滤 NSDictionary

将 Plist (NSString) 解析为 NSDictionary

如何将 NSString 转换为 NSDictionary?

按索引获取 NSDictionary 键?