我正在尝试创建一个通用方法,该方法将SEL
作为参数并将其传递给dispatch_async
以供执行,但我无法如何执行传入的SEL。
这里的任何人都可以帮助我。
// Test.m
-(void) executeMe
{
NSLog(@"Hello");
}
- (void)viewDidLoad
{
[super viewDidLoad];
SEL executeSel = @selector(executeMe);
[_pInst Common_Dispatch: executeSel];
}
// Common.m
-(void) Common_Dispatch:(SEL) aSelector
{
dispatch_async(iDispatchWorkerQueue, ^(void) {
// How to execute aSelector here?
});
}
答案 0 :(得分:6)
您需要在Common_Dispatch
方法上设置“target”参数,因为您需要在特定对象上调用选择器。
- (void)viewDidLoad {
[super viewDidLoad];
SEL executeSel = @selector(executeMe);
[_pInst Common_Dispatch:executeSel target:self];
}
- (void)Common_Dispatch:(SEL)aSelector target:(id)target {
dispatch_async(iDispatchWorkerQueue, ^(void) {
[target performSelector:aSelector];
});
}
BTW - 标准命名约定规定方法名称应以小写开头并使用camelCase。你的方法应该是commonDispatch。
答案 1 :(得分:2)
或者,您可以使用块参数,例如
- (void)commonDispatch:(void (^)(void))block
{
dispatch_async(iDispatchWorkerQueue, block);
}
然后你将其调用为:
[_pInst commonDispatch:^{
[self executeMe];
}];
这样,您可以使用此调度程序调用不带参数的executeMe
方法,或者调度带有大量参数的方法,例如:
[_pInst commonDispatch:^{
[self executeOtherMethodForURL:url requestType:type priority:priority];
}];
或者更复杂的情况:
[_pInst commonDispatch:^{
[self executeOtherMethodForURL:url requestType:type priority:priority];
dispatch_async(dispatch_get_main_queue(), ^{
// update my UI to say that the request is done
});
}];
答案 2 :(得分:0)
您只需调用performSelector方法,如下所示:
[self performSelector:aSelector];
还有其他有用的覆盖来执行你会发现的选择。
修改强>
选择器的目标也必须作为参数传递:
// Test.m
-(void) executeMe
{
NSLog(@"Hello");
}
- (void)viewDidLoad
{
[super viewDidLoad];
SEL executeSel = @selector(executeMe);
[_pInst Common_Dispatch: executeSel target:self];
}
// Common.m
-(void) Common_Dispatch:(SEL) aSelector target:(id)target
{
dispatch_async(iDispatchWorkerQueue, ^(void) {
[target performSelector:aSelector];
});
}