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?)
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];
来源:https://stackoverflow.com/questions/38930228/pass-block-as-parameter-in-my-case