pass block as parameter in my case

情到浓时终转凉″ 提交于 2019-12-04 22:06:27

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

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

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

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