Objective c 实现不区分大小写的NSMutableDictionary
我尝试从Objective c 实现不区分大小写的NSMutableDictionary,objective-c,oop,inheritance,Objective C,Oop,Inheritance,我尝试从NSMutableDictionary继承,以便使用不区分大小写的键实现dictionary。以下是我的实现: @interface NSMutableDictionaryLowerCase : NSMutableDictionary<NSString*, NSString *> @end @implementation NSMutableDictionaryLowerCase -(NSString *)objectForKey:(NSString *)aKey
NSMutableDictionary
继承,以便使用不区分大小写的键实现dictionary。以下是我的实现:
@interface NSMutableDictionaryLowerCase : NSMutableDictionary<NSString*, NSString *>
@end
@implementation NSMutableDictionaryLowerCase
-(NSString *)objectForKey:(NSString *)aKey {
return [[super objectForKey:aKey] lowercaseString];
}
@end
但是,当将其与以下代码一起使用时,它捕获了setValue
上的异常,并显示以下消息:
[NSMutableDictionary setObject:forKey:]:仅为抽象类定义的方法。定义-[NSMutableDictionaryLowerCase setObject:forKey:]!'代码>
我不明白,NSMutableDictionary
不应该是抽象类,我认为这个方法实现已经存在了。。。我做错了什么?来自以下文件:
将注释子类化
通常不需要将NSMutableDictionary
子类化。如果确实需要自定义行为,通常最好考虑组合而不是子类。
覆盖的方法
在子类中,必须重写其两个基元方法:
- setObject(u0;:forKey:)
- removeObject(forKey:)
您还必须重写NSDictionary
类的基元方法。多亏了@Larme,下面是修复方法:
@interface NSMutableDictionaryLowerCase : NSMutableDictionary<NSString*, NSString *> {
NSMutableDictionary* _proxy;
}
@end
@implementation NSMutableDictionaryLowerCase
- (instancetype)init {
if (self = [super init]) {
_proxy = [[NSMutableDictionary alloc] init];
}
return self;
}
-(NSString *)objectForKey:(NSString *)aKey {
return [_proxy objectForKey:[aKey lowercaseString]];
}
-(void)setObject:(NSString *)anObject forKey:(NSString *)aKey{
[_proxy setObject:anObject forKey:[aKey lowercaseString]];
}
@end
@接口NSMutableDictionaryLowerCase:NSMutableDictionary{
NSMutableDictionary*\u代理;
}
@结束
@NSMutableDictionaryLowerCase的实现
-(instancetype)初始化{
if(self=[super init]){
_proxy=[[NSMutableDictionary alloc]init];
}
回归自我;
}
-(NSString*)objectForKey:(NSString*)aKey{
return[_proxyobjectforkey:[aKey lowercasesetring]];
}
-(void)setObject:(NSString*)一个对象forKey:(NSString*)aKey{
[_proxysetobject:anObject forKey:[aKey lowercasesetring]];
}
@结束
@interface NSMutableDictionaryLowerCase : NSMutableDictionary<NSString*, NSString *> {
NSMutableDictionary* _proxy;
}
@end
@implementation NSMutableDictionaryLowerCase
- (instancetype)init {
if (self = [super init]) {
_proxy = [[NSMutableDictionary alloc] init];
}
return self;
}
-(NSString *)objectForKey:(NSString *)aKey {
return [_proxy objectForKey:[aKey lowercaseString]];
}
-(void)setObject:(NSString *)anObject forKey:(NSString *)aKey{
[_proxy setObject:anObject forKey:[aKey lowercaseString]];
}
@end