如何在objective-c中将方法设置为类方法的参数

ale*_*ssa 5 iphone methods class ios

我在编写一个有方法有参数的类方法时遇到了问题.

该函数在"SystemClass.m/h"类中

//JSON CALL
+(void)callLink:(NSString*)url toFunction:(SEL)method withVars:(NSMutableArray*)arguments {
    if([self checkConnection])
    {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData *datas = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
            [arguments addObject:datas];
            [self performSelectorOnMainThread:@selector(method:) withObject:arguments waitUntilDone:YES];
        });
    }else{
        [self alertThis:@"There is no connection" with:nil];
    }
}
Run Code Online (Sandbox Code Playgroud)

该函数的作用是调用JSON url,并将数据提供给Method

我这样使用它:

[SystemClass callLink:@"http://www.mywebsite.com/call.php" toFunction:@selector(fetchedInfo:) withVars:nil];
Run Code Online (Sandbox Code Playgroud)

但它像这样崩溃:

因未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'+ [SystemClass方法:]:无法识别的选择器发送到类0x92d50'

你可以帮帮我吗?无论如何,我正试图找到解决方案!

谢谢,亚历克斯

Ash*_*bay 5

在你的callLink方法中,你已经将一个选择器作为参数(它是名为"method"的参数).此外,您需要再添加一个参数,因为应该从实现此方法的对象调用"method"参数(在您给我们的示例中,当您使用时,应用程序将尝试从SystemClass调用名为"method"的方法)电话:

[self performSelectorOnMainThread:method withObject:arguments waitUntilDone:YES];
Run Code Online (Sandbox Code Playgroud)

这里的self是SystemClass,SystemClass中似乎不存在这样的方法,这就是崩溃的原因.所以在参数中添加一个目标(一个id对象):

+(void)callLink:(NSString*)url forTarget:(id) target toFunction:(SEL)method withVars:(NSMutableArray*)arguments;
Run Code Online (Sandbox Code Playgroud)

因此,对于以下行,您应该只给出选择器并在目标对象上调用此选择器:

[target performSelectorOnMainThread:method withObject:arguments waitUntilDone:YES];
Run Code Online (Sandbox Code Playgroud)

并不是 :

[self performSelectorOnMainThread:@selector(method:) withObject:arguments waitUntilDone:YES];
Run Code Online (Sandbox Code Playgroud)

改进:

在调用选择器之前,你应该检查目标是否响应选择器执行类似的操作(它会阻止你的应用程序崩溃).而不是这样做:

[target performSelectorOnMainThread:method withObject:arguments waitUntilDone:YES];
Run Code Online (Sandbox Code Playgroud)

做这个 :

if([target respondsToSelector:method])
{
  [target performSelectorOnMainThread:method withObject:arguments waitUntilDone:YES];
}
else
{
  //The target do not respond to method so you can inform the user, or call a NSLog()...
}
Run Code Online (Sandbox Code Playgroud)