How can I access properties that are not compatible with KVC, only with their name?

Context: I have several CGPathRef in a custom class derived from NSObject with a name model. I am looking for a way to return a specific CGPathRef based on the string that I generate at runtime.

A simplified example if I can use 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);
        }
}

Question: How can I access properties that are not compatible with KVC (CGPathRef), only with their name represented as a string?

+3
source share
3 answers

You can use NSInvocation for this. Sort of:

// 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 (, , ).

EDIT: .

+2

cocoa -dev. : .

, . , KVC.

, , UIBezierPath, CGPath .

, , , KVC. , NSValue .

, valueForUndefinedKey:, , . , . ( , CALayer). , , , , KVC... , . "" .

, KVC , .

+1

What I would do (and sometimes do) is to wrap the CGPathRef in UIBezierPath just so that it is an object and has all the benefits associated with it, including KVC, the ability to embed it in NSArray or NSDictionary, and ARC memory management. In the end, this is exactly what UIBezierPath (more or less).

0
source

All Articles