2012-05-06 56 views
1

我有一個包含了一套做的方法幾乎相同的實現:的OBJ-C:如何使用方法轉發,以提高重複方法實現

- (NSString *) specialKey{ 
    [self.mySpecialDictionary valueForKey:@"specialKey"]; 
} 

- (NSString *) anotherKey{ 
    [self.mySpecialDictionary valueForKey:@"mySpecialKey1"]; 
} 

我現在可以方便地使用這些干將像這樣:

NSString *foo = [Setting sharedInstance].specialKey; 

我想我現在應該能夠確定我的屬性dynamic,使一個實現所有這些情況下,因爲這是我在我的字典中查找字符串將永遠是姓名o吸氣劑。我很確定這應該在Objective-C中可行,但我不知道如何實現這一點。

+0

你的問題是什麼? – Seany242

+0

我更新了我的問題 – Besi

+0

你的意思是你想要一個單一的getter到多個屬性? – Saad

回答

1

答案就在你的問題。嘗試方法轉發:

- (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

+0

我在我的TableKit庫中使用了這種技術。 [代理對象](https://github.com/onegray/UITableKit/blob/master/TableKit/Attributes/TKAttrProxy.m)捕獲所有嘗試寫入屬性並將其保存在屬性數組中。 – onegray

0

這是怎麼回事?

- (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 ... 
     } 
    } 
+1

你忘了返回值.. – Peres

+0

我很累,謝謝你.. ;-) – MJB

+0

我想保留我的財產,但使用動態執行 – Besi