gpt4 book ai didi

iphone - Objective-C : How to improve repetitive method implementations using method forwarding

转载 作者:行者123 更新时间:2023-11-29 13:36:22 25 4
gpt4 key购买 nike

我有一个实现,其中包含一组几乎相同的方法:

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

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

我现在可以像这样方便地使用这些 getter:

NSString *foo = [Setting sharedInstance].specialKey;

我想我现在应该能够定义我的属性 dynamic 并为所有这些情况制作 one 实现,因为我在字典中查找的字符串将始终是 setter/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

关于iphone - Objective-C : How to improve repetitive method implementations using method forwarding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10474523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com