我有一个函数,它以块作为参数:
typedef void (^ MyBlock)(int);
-(void)doTask:(MyBlock)theBlock{
...
}
我需要在另一个线程上运行上面的函数,我想使用- performSelector:onThread:withObject:waitUntilDone:,我当前的代码:
NSThread *workerThread = [[NSThread alloc] init];
[workerThread start];
[self performSelector:@selector(doTask:)
onThread:workerThread
withObject:???
waitUntilDone:NO];
但是,如何通过这种方法传递MyBlock
参数? (请不要建议GCD,我想知道如何处理我当前的代码,是否可能?)
答案 0 :(得分:1)
这个答案假设您正在使用ARC。如果你不是那么你需要多做一点,但总的来说答案是一样的。
但是,如何通过这种方法传递
MyBlock
参数?
块是一个对象,你不需要做任何特殊的事情。 E.g:
[self performSelector:@selector(doTask:)
onThread:workerThread
withObject:^(int arg){ NSLog(@"block passed: %d", arg); }
waitUntilDone:NO];
HTH
答案 1 :(得分:0)
[self performSelector:@selector(someMethod)
onThread:[Your thread]
withObject:[your object]
waitUntilDone:NO];
-(void)someMethod
{
[self doTask:^(int intValue) {
// Do your task
}];
}
答案 2 :(得分:0)
首先创建这样的线程,使其处于活动状态,并且可以从该线程调用方法
-(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];
然后写这样的东西
-(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];