iOS Objective-C - 使用NSClassFromString动态创建的类上的调用类方法

时间:2017-01-18 03:13:29

标签: ios objective-c

我知道我可以通过执行[MyClass myMethod];

来调用[NSClassFromString(@"MyClass") performSelector:@selector(myMethod)];之类的类方法

我现在正试图这样做:

[MyClass configureWithNum:@"12345"
       andNumber:@"2312312"
       options:nil
       completion:^(NSArray<SecondClass*>* array) {}
     ];

当我这样做时:

[NSClassFromString(@"MyClass") performSelector:@selector(configureWithNum)
            withObject:@"12345"
            withObject:@"2312312"
            withObject:nil
            withObject:^(NSArray<SecondClass*>* array) {}];

抛出Undeclared selection 'configureWithNum'

似乎performSelector withObject调用仅适用于一个参数。所以我怀疑我需要使用objc_msgSend执行类似this的操作,但我似乎无法使格式正确。

我认为this SO走在正确的轨道上 - 但我似乎无法做到正确。当我这样做时:

objc_msgSend(NSClassFromString(@"MyClass"), sel_getUid("configureWithNum:andNumber:options:completion:"), @"12345", @"2312312", nil, ^(NSArray<AdColonyZone*>* zones) {});

它给我一个implicit declaration of function 'objc_msgSend' is invalid in C99错误。

如何使用objc_msgSendperformSelector: withObject:来实现此调用?

2 个答案:

答案 0 :(得分:0)

因为没有多个withObject的方法。您应该将所有数据封装在单个对象(如NSArray或NSDictionary)中,然后将其作为参数传递。

例如:

NSArray * arrayParams = 
[NSArray arrayWithObjects: @"firstParams", @"secondParams", nil];

[self performSelector:@selector(configureWithNum:) 
           withObject:arrayParams];

答案 1 :(得分:0)

Implicit declaration of function 'objc_msgSend' is invalid in C99错误表示您未包含必需的标头。

#include <objc/message.h>

应该解决这个问题。

相关问题