问题描述
||
嗨,我有一个NSMutableDicitionary包含小写和大写键。所以目前我不知道如何使用目标c在字典中找到该键。
解决方法
分类救援。
好的,这是一个旧帖子...
@interface NSDictionary (caseINsensitive)
-(id) objectForCaseInsensitiveKey:(id)aKey;
@end
@interface NSMutableDictionary (caseINsensitive)
-(void) setObject:(id) obj forCaseInsensitiveKey:(id)aKey ;
@end
@implementation NSDictionary (caseINsensitive)
-(id) objectForCaseInsensitiveKey:(id)aKey {
for (NSString *key in self.allKeys) {
if ([key compare:aKey options:NSCaseInsensitiveSearch] == NSOrderedSame) {
return [self objectForKey:key];
}
}
return nil;
}
@end
@implementation NSMutableDictionary (caseINsensitive)
-(void) setObject:(id) obj forCaseInsensitiveKey:(id)aKey {
for (NSString *key in self.allKeys) {
if ([key compare:aKey options:NSCaseInsensitiveSearch] == NSOrderedSame) {
[self setObject:obj forKey:key];
return;
}
}
[self setObject:obj forKey:aKey];
}
@end
请享用。
,您可以控制密钥的创建吗?如果这样做的话,在创建密钥时,我只会强制将密钥更改为小写或大写。这样,当您需要查找内容时,就不必担心大小写混合的情况。
,您可以执行此操作以获取对象作为子类的替代方法。
__block id object;
[dictionary enumerateKeysAndObjectsWithOptions:NSEnumerationConcurrent
UsingBlock:^(id key,id obj,BOOL *stop){
if ( [key isKindOfClass:[NSString class]] ) {
if ( [(NSString*)key caseInsensitiveCompare:aString] == NSOrderedSame ) {
object = obj; // retain if wish to.
*stop = YES;
}
}
}];
如果您发现自己在代码中经常这样做,则可以使用#define
速记。
,不要以为有任何简单的方法。最好的选择是创建NSMutableDictionary
的子类,并覆盖objectForKey
和setObject:ForKey
连词。然后,在您重写的方法中,确保在将所有键传递给超类方法之前,将所有键都转换为小写(或大写)。
符合以下要求的方法应该起作用:
@Interface CaseInsensitveMutableDictionary : MutableDictionary {}
@end
@implementation CaseInsensitveMutableDictionary
- (void) setObject: (id) anObject forKey: (id) aKey {
[super setObject:anObject forKey:[skey lowercaseString]];
}
- (id) objectForKey: (id) aKey {
return [super objectForKey: [aKey lowercaseString]];
}
@end