我想让NSDictionary抛出异常,而不是在找不到密钥时返回nil。
我已经完成了一些研究,好吧,我明白了,继承任何集合类是个坏主意。那么,实现这一目标的最佳方法是什么?
注意我想保留下标语法,通过文字创建,或者至少从中获取最多。
类别方法很简单但不允许我使用下标语法:
id value = dict[@"non-existing-key"]; // throws exception
包装器方法不允许我使用文字创建:
MyDictWrapper *dict = @{ @"key" : @"value" }; // this returns a standard NSDictionary
有没有办法在找不到该项时进行字典抛出和异常,并保留这个非常有用且方便的语法?
答案 0 :(得分:1)
void swizzleInstance(SEL originalSl, SEL swizzledSl, Class originalCl, Class swizzledCl) {
Method originalMethod = class_getInstanceMethod(originalCl, originalSl);
Method swizzledMethod = class_getInstanceMethod(swizzledCl, swizzledSl);
method_exchangeImplementations(originalMethod, swizzledMethod);
}
@implementation NSDictionary(ExceptionForKey)
- (id)objectForKey_m:(NSString *)aKey
{
id object = [self objectForKey_m:aKey];
if (!object) {
[NSException exceptionWithName:@"Object not found"
reason:[@"Object not found for key: " stringByAppendingString:aKey]
userInfo:nil];
}
return object;
}
+ (void)load {
swizzleInstance(@selector(objectForKey:),
@selector(objectForKey_m:),
[NSDictionary class],
[NSDictionary class]);
}
@end