gpt4 book ai didi

objective-c - 如何仅使用名称访问不符合 KVC 的属性?

转载 作者:搜寻专家 更新时间:2023-10-30 20:09:14 24 4
gpt4 key购买 nike

上下文:我在自定义类中有几个 CGPathRef,派生自 NSObject,名为 model。我正在寻找一种返回特定 CGPathRef 的方法,该方法基于我在运行时生成的字符串。

简化示例,如果我可以使用 KVC:

#model.h
@property (nonatomic) CGMutablePathRef pathForwardTo1;
@property (nonatomic) CGMutablePathRef pathForwardTo2;
@property (nonatomic) CGMutablePathRef pathForwardTo3;
...


#someVC.m
-(void)animateFromOrigin:(int)origin toDestination:(int)destination{
int difference = abs(origin - destination);
for (int x =1; x<difference; x++) {
NSString *pathName = [NSString stringWithFormat:@"pathForwardTo%d", x];
id cgPathRefFromString = [self.model valueForKey:pathName];
CGPathAddPath(animationPath, NULL, cgPathRefFromString);
}
}

问题:我如何访问不符合 KVC 的属性 (CGPathRef),仅将其名称表示为字符串?

最佳答案

你应该能够为此使用 NSInvocation。像这样的东西:

// Assuming you really need to use a string at runtime. Otherwise, hardcode the selector using @selector()
SEL selector = NSSelectorFromString(@"pathForwardTo1");
NSMethodSignature *signature = [test methodSignatureForSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setSelector:selector];
[invocation setTarget:test];
[invocation invoke];

CGMutablePathRef result = NULL;
[invocation getReturnValue:&result];

您也可以直接使用适当的 objc_msgSend 变体来执行此操作,但 NSInvocation 更容易(尽管可能慢得多)。

编辑:我放了一个简单的小测试程序 here .

关于objective-c - 如何仅使用名称访问不符合 KVC 的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21564237/

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