pass block as parameter in my case

2019-04-17 15:47发布

I have a function which takes a block as parameter:

typedef void (^ MyBlock)(int);

-(void)doTask:(MyBlock)theBlock{
 ...
}

I need to run above function on another thread, I want to use - performSelector:onThread:withObject:waitUntilDone: , my current code:

NSThread *workerThread = [[NSThread alloc] init];
[workerThread start];

[self performSelector:@selector(doTask:) 
             onThread:workerThread 
           withObject:???
        waitUntilDone:NO];

BUT, How can I pass MyBlock parameter with this approach? (Please don't suggest GCD, I am wondering how can I do with my current code, is it possible?)

3条回答
啃猪蹄的小仙女
2楼-- · 2019-04-17 16:09

This answer assumes you are using ARC. If you are not then you need to do a little more, but overall the answer is the same.

BUT, How can I pass MyBlock parameter with this approach?

A block is an object, you don't need to do anything special. E.g.:

[self performSelector:@selector(doTask:) 
             onThread:workerThread 
           withObject:^(int arg){ NSLog(@"block passed: %d", arg); }
        waitUntilDone:NO];

HTH

查看更多
Fickle 薄情
3楼-- · 2019-04-17 16:09
[self performSelector:@selector(someMethod) 
         onThread:[Your thread] 
       withObject:[your object]
    waitUntilDone:NO];

-(void)someMethod
{
   [self doTask:^(int intValue) {
        // Do your task
    }];
}
查看更多
beautiful°
4楼-- · 2019-04-17 16:21

First create thread like this so that it is alive and you can call methods from that thread

-(void) myThreadMainMethod: (id) sender {

    @autoreleasepool {
        NSRunLoop *runloop = [NSRunLoop currentRunLoop];
        [runloop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];

        while (true) { // add your condition for keeping the thread alive 
            [runloop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        }
    }
}

  NSThread* workerThread = [[NSThread alloc] initWithTarget:self
                                                 selector:@selector(myThreadMainMethod:)
                                                   object:nil];

    [workerThread start];

Then write something like this

-(void)doTask:(MyBlock)theBlock{
        NSLog(@"do task called now execute the block");
        theBlock(1);
    }

    MyBlock block1 = ^(int a) {
        NSLog(@"integer %i", a);
    };

    [self performSelector:@selector(doTask:)
                 onThread:[NSThread mainThread]
               withObject:block1
            waitUntilDone:NO];
查看更多
登录 后发表回答