简体   繁体   中英

performSelectorInBackground with more that 2 parameters

I am trying to execute a performSelectorInBackground with an object and a block. I am aware of this answer but it wasn't helpful for my case. The reason it wasn't helpful it's because the answer there is for passing 2 parameters as objects but in my case is passing an object and a callback.

This is my code:

static ACallBack aCallback;
- (void)doSometginh:(Book*)aBook callback:(ClassCallback)aCallback
{
    [self performSelectorInBackground:@selector(doVeryLongTask1:callback:) withObject:aPerson withObject:aCallback];
}

The code is wrong because it wont accept the second parameter. Any ideas how to parse the block as second parameter?

Why don't you use Grand Central Dispatch ? You could do something like:

static TestClassCallback savedCallback;
- (void)doSometginh:(Book*)aBook callback:(ClassCallback)aCallback {
    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        [self doVeryLongTask1:aPerson callback:aCallback];
    });
}

You can perform the callback in the main thread with this code:

dispatch_async(dispatch_get_main_queue(), ^(void){
    callback();
});

EDIT: Those calls can be nested. For example if you want to have Task1 and Task2 that run in the background and you want to update something on the mainthread between them:

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
    // Task 1
    dispatch_async(dispatch_get_main_queue(), ^(void){
        // Update on main thread
        dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
            // Task 2
        });
    });
});

Add another call of dispatch_async(dispatch_get_main_queue(), ^(void){ after // Task 2 to add a final callback on the mainthread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM