用反射创建对象

时间:2014-04-25 13:54:28

标签: objective-c reflection

我有一个类,我需要使用反射创建一个Object。

说我有以下课程(通过课程转储获得):

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

现在我想用反射创建一个新对象:

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

如何传递辅助参数?

请注意,我无法更改SomeClass

的布局

2 个答案:

答案 0 :(得分:1)

如果要传递2个参数,可以使用performSelector:withObject:withObject:方法。如果你需要传递两个以上最好的方法是创建自定义类,它将包含所有参数并使用performSelector:withObject:方法传递类。你不能传递原始变量,所以用NSNumber替换int。

// EXTENDED

如果要传递2个以上的参数并且无法修改接受自定义对象的方法,可以使用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];
}

答案 1 :(得分:1)

为类创建标题并将其导入。使用标题与班级互动(因此您不会进行任何performSelector...次调用)。

如果由于某种原因您不能这样做,请使用NSInvocation代替performSelector...