抱歉新手问题(也许)。我正在为ios开发一个应用程序,我正在尝试从主线程中执行外部xml读取,以便在调用正在进行魔术时不冻结ui。
这是我知道使进程不在目标c的主线程中执行的唯一方法
[self performSelectorInBackground:@selector(callXml)
withObject:self];
所以我把我的电话封装成了一个函数
- (void)callXml{
[RXMLElement elementFromURL:[NSURL URLWithString:indXML]];
}
现在我必须使字符串indXML成为函数的参数,以便根据需要调用不同的xml。 像
这样的东西 - (void)callXml:(NSString *) name{
[RXMLElement elementFromURL:[NSURL URLWithString:indXML]];
}
在这种情况下,对performSelector的调用如何改变?如果我以通常的方式做到这一点,我会得到语法错误:
[self performSelectorInBackground:@selector(callXml:@"test")
withObject:self];
答案 0 :(得分:15)
[self performSelectorInBackground:@selector(callXml:)
withObject:@"test"];
ie:你传入的作为withObject:成为你方法的参数。
正如您感兴趣的那样,您可以使用GCD来实现这一目标:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self callXml:@"test"];
// If you then need to execute something making sure it's on the main thread (updating the UI for example)
dispatch_async(dispatch_get_main_queue(), ^{
[self updateGUI];
});
});
答案 1 :(得分:8)
对于此
- (void)callXml:(NSString *) name{
[RXMLElement elementFromURL:[NSURL URLWithString:indXML]];
}
你可以像这样打电话
[self performSelectorInBackground:@selector(callXml:)
withObject:@"test"];
如果您的方法有参数,则:与method_name一起使用,并将参数作为 withObject 参数传递
答案 2 :(得分:1)
您使用的选择器需要与方法名称完全匹配 - 方法名称包含冒号(:)字符。所以你的选择器应该是:
@selector(callXml:)
如果要传递参数。
如果您需要传递更复杂的数据,您有3个选项:
NSArray
或NSDictionary
答案 3 :(得分:1)
嗨试试这个,
RXMLElement *rootXML= [self performSelectorInBackground:@selector(callXml:)
withObject:@"test"];
- (RXMLElement *)callXml:(NSString *) name{
NSLog(@"%@",name);//Here passed value will be printed i.e test
return [RXMLElement elementFromURL:[NSURL URLWithString:indXML]];
}
答案 4 :(得分:0)
由于performSelectorInBackground:withObject:
只接受一个对象参数。解决此限制的一种方法是将参数的字典(或数组)传递给“包装器”方法,该方法解构参数并调用实际方法。