Question

I have a class where I need to create an Object from using reflection.

say I have the following class (got by class-dump or else):

@interface SomeClass : NSObject
{
    - (void)dealloc;
    - (id)initWithArguments:(char *)value1 arg2:(int)value2;
}

Now I want to create a new object from it using reflection:

Class theClass = [instance class];
SEL selector = NSSelectorFromString(@"initWithArguments:arg2:");
id newInstanceOfClass = [[theClass alloc] performSelector:selector withObject:????];

How can I pass the secondary parameter?

Note that I am not able to change the layout of SomeClass.

Was it helpful?

Solution

You can use performSelector:withObject:withObject: method if you are going to pass 2 parameters. If you need to pass more than two the best way is create custom class which will hold all of your parameters and pass the class with performSelector:withObject: method. You cannot pass primitive variable so replace int with NSNumber.

//EXTENDED

If you want to pass more than 2 parameter and you cannot amend the method to accept custom object you can use NSInvocation:

// List of yours parameters
NSString *s1 = @"parameter 1";
NSString *s2 = @"parameter 2";
NSString *s3 = @"parameter 3";

// your selector
SEL selector = @selector(testParam1:param2:param3:);

if([self respondsToSelector:selector]) { // just to make sure there is right method to run,
// you have to change it to [theClass alloc] respond to selector instead of self
    NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:selector]];
    [inv setSelector:selector];
    [inv setTarget:self]; // change it to the object you want to call the parameter (theClass)

    [inv setArgument:&s1 atIndex:2]; //arguments 0 and 1 are reserved for self and cmd you have to start passing your parameters with index 2
    [inv setArgument:&s2 atIndex:3];
    [inv setArgument:&s3 atIndex:4];
    [inv invoke];
}

OTHER TIPS

Create a header for the class and import it. Use the header to interact with the class (so you won't be making any performSelector... calls).

If for some reason you can't do that, use NSInvocation instead of performSelector....

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top