Vas*_*lis 0 overriding objective-c nsmutabledictionary
我需要覆盖NSMutableDictionary的valueForKey:方法.我想检查一个特定的值,做一些操作并返回它.我应该注意哪些要点?如果出现问题,请纠正我,例如:
- (id)valueForKey:(NSString*)key {
id val = [super valueForKey:key];
if([val isKindOfClass:[NSString class]] && [val isEqualToString:@"<null>"]) {
return @"No Value";
}
else {
return val;
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢
您可能不想覆盖valueForKey,因为NSDictionary并且NSMutableDictionary是隐藏其后面的类集群的抽象基类.根据他们的文档,在一个直接的子类中,你需要重新实现所有:
实现一个假装成NSMutableDictionary的替代类更容易,但是将它不理解的任何调用转发给实际的NSMutableDictionary.你可以通过forwardingTargetForSelector做到:.
例如
@interface MyFakeDictionary: NSObject
{
NSMutableDictionary *theRealDictionary;
}
/* reimplement whatever init methods you want to use */
- (id)valueForKey:(id)key;
@end
...
@implementation MyFakeDictionary
- (id)valueForKey:(id)key
{
id val = [theRealDictionary objectForKey:key];
/* etc, as you like */
}
- (id)forwardingTargetForSelector:(SEL)aSelector
{
return theRealDictionary;
}
@end
Run Code Online (Sandbox Code Playgroud)
所以MyFakeDictionary和NSMutableDictionary之间没有继承关系,但是如果你发送一个它不理解的选择器到MyFakeDictionary(就像你替换的那个之外的任何普通字典消息),NSObject的内置逻辑将重定向它们成员theRealDictionary.它有一个'而不是'是一个',具有透明的消息转发功能,因此可以方便地解决类集群的任何问题.
| 归档时间: |
|
| 查看次数: |
2963 次 |
| 最近记录: |