Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 如何将SEL传递给dispatch\u异步方法_Objective C_Selector_Grand Central Dispatch - Fatal编程技术网

Objective c 如何将SEL传递给dispatch\u异步方法

Objective c 如何将SEL传递给dispatch\u异步方法,objective-c,selector,grand-central-dispatch,Objective C,Selector,Grand Central Dispatch,我试图创建一个通用方法,将SEL作为参数,并将其传递给dispatch\u async执行,但我不知道如何执行传入的SEL。 这里有人能帮我吗 // Test.m -(void) executeMe { NSLog(@"Hello"); } - (void)viewDidLoad { [super viewDidLoad]; SEL executeSel = @selector(executeMe); [_pInst Common_Dispatch: exec

我试图创建一个通用方法,将
SEL
作为参数,并将其传递给
dispatch\u 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?
    });
}

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

[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];
    });
}
您还需要在
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];
    });
}

顺便说一句,标准命名约定规定,方法名称应以小写字母和用例开头。您的方法应该是commonDispatch。

或者,您可以使用块参数,例如

- (void)commonDispatch:(void (^)(void))block
{
    dispatch_async(iDispatchWorkerQueue, block);
}
然后,您可以将其调用为:

[_pInst commonDispatch:^{
    [self executeMe];
}];
通过这种方式,您可以使用此dispatcher调用不带参数的方法,如
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
    });
}];

除了选择器不在
self
中之外。这是另一个类的方法。哦,是的,我没注意到。目标也必须通过。