pass block as parameter in my case

依然范特西╮ 提交于 2019-12-22 01:48:26

问题


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?)


回答1:


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




回答2:


[self performSelector:@selector(someMethod) 
         onThread:[Your thread] 
       withObject:[your object]
    waitUntilDone:NO];

-(void)someMethod
{
   [self doTask:^(int intValue) {
        // Do your task
    }];
}



回答3:


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];


来源:https://stackoverflow.com/questions/38930228/pass-block-as-parameter-in-my-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!