3

コンテキスト: という名前の NSObject から派生したカスタム クラスにいくつかの CGPathRef があり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) に、文字列として表された名前だけでアクセスするにはどうすればよいですか?

4

3 に答える 3

2

これには 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 の方が簡単です (ただし、かなり遅い可能性があります)。

編集:ここに簡単な小さなテスト プログラムを置きます。

于 2014-02-04T22:52:56.447 に答える