iOS:如何在后台线程中努力处理数据?

Jim*_*Jim 3 multithreading ios

我有一个方法,如:

- (BOOL)shouldDoSomeWork {
   BOOL result = // here I need do hard work with data in background thread and return result, so main thread should wait until the data is calculated and then return result;
   return result;
}
Run Code Online (Sandbox Code Playgroud)

如何实现?

Jam*_*ter 5

你在找这个:

-(void) startWork
{ 
    //Show activity indicator
    [NSThread detachNewThreadSelector:@selector(doSomeWork) toTarget:self withObject:nil];
}

-(void) doSomeWork
{
    NSAutoreleasePool *pool = [NSAutoreleasePool new];
    //Do your work here
    [pool release];
    [self performSelectorOnMainThread:@selector(doneWork) withObject:nil waitUntilDone:NO];
}  

-(void) doneWork
{
   //Hide activity indicator  
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您希望主线程在此线程上等待,请不要使用线程 (3认同)
  • 没有!NSThread不是要走的路!查看NSOperationQueue或盛大的中央调度 (3认同)

one*_*ray 5

示例如何使用GCD执行此操作:

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // Your hard code here
        // ...

        //BOOL result = ...

        dispatch_async(dispatch_get_main_queue(),^{
            [self callbackWithResult:result];  // Call some method and pass the result back to main thread
        });

    });
Run Code Online (Sandbox Code Playgroud)