4

我正在尝试创建一个将 aSEL作为参数并将其传递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?
    });
}
4

3 回答 3

6

您的Common_Dispatch方法还需要有一个“目标”参数,因为您需要在特定对象上调用选择器。

- (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];
    });
}

顺便说一句 - 标准命名约定规定方法名称应以小写开头并使用 camelCase。你的方法应该是 commonDispatch。

于 2013-07-22T01:50:57.650 回答
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
    });
}];
于 2013-07-22T01:55:59.730 回答
0

您只需调用 performSelector 方法,如下所示:

[self performSelector:aSelector];

您会发现 performSelector 还有其他有用的覆盖。

编辑

选择器的目标也必须作为参数传递:

// 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];
    });
}
于 2013-07-22T01:41:36.607 回答