[英]Obj-C: How to improve repetitive method implementations using method forwarding
我有一個包含一組方法的實現,它們的作用幾乎相同:
- (NSString *) specialKey{
[self.mySpecialDictionary valueForKey:@"specialKey"];
}
- (NSString *) anotherKey{
[self.mySpecialDictionary valueForKey:@"mySpecialKey1"];
}
我現在可以像這樣方便地使用這些吸氣劑:
NSString *foo = [Setting sharedInstance].specialKey;
我想我現在應該可以dynamic
定義我的Properties並為所有這些情況做一個實現,因為我在字典中查找的字符串將始終是getter的名稱。 我很確定這應該在Objective-C中是可行的,但是我不知道如何實現。
答案就在您的問題上。 嘗試方法轉發:
- (NSMethodSignature*) methodSignatureForSelector:(SEL)selector
{
return [mySpecialDictionary methodSignatureForSelector:@selector(valueForKey:)];
}
- (void) forwardInvocation:(NSInvocation *)invocation
{
NSString* propertyName = NSStringFromSelector(invocation.selector);
[invocation setSelector:@selector(valueForKey:)];
[invocation setArgument:&propertyName atIndex:2];
[invocation invokeWithTarget:mySpecialDictionary];
}
當然,要擺脫編譯器警告,需要明確定義每個屬性
@property (nonatomic, readonly) NSString* specialKey;
@property (nonatomic, readonly) NSString* anotherKey;
並為他們提供@dynamic
。
那這個呢?
- (NSString *)valueForKey:(NSString *)key
{
return [self.mySpecialDictionary valueForKey:key];
}
這將返回所提供密鑰的值。 或這樣更靈活地使用
- (NSString *)valueForKey:(id)key
{
if([key isKindOfClass:[NSString class]]){
return [self.mySpecialDictionary valueForKey:key];
}
}
甚至這個
- (id)valueForKey:(id)key
{
if([key isKindOfClass:[NSString class]]){
return [self.mySpecialDictionary valueForKey:key];
} else if (..){
// catch more possible keys here ...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.