Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a SEL to dispatch_async method

I am trying to create a generic method that takes a SEL as a parameter and passes it to dispatch_async for execution, but i am clueless how to execute the passed in SEL. Can anyone here help me please.

// 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?
    });
}
like image 558
newdev1 Avatar asked Feb 16 '23 20:02

newdev1


1 Answers

You need to also have a "target" parameter on your Common_Dispatch method since you need to call the selector on a specific object.

- (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 - standard naming conventions state that method names should begin with lowercase and use camelCase. Your method should be commonDispatch.

like image 188
rmaddy Avatar answered Feb 28 '23 05:02

rmaddy