Sunday, September 18, 2011

How to execute tasks in separate threads in Objective C

This code snippet shows how you can execute tasks  in two separate threads:


    dispatch_queue_t download_queue = dispatch_queue_create("Home View Controller", NULL);
    //first thread
    dispatch_async(download_queue, ^{               
        NSError *error = nil;
        NSArray *array = [[NetworkService getThingsByAccountId:accountId error:&error] positions];        
        //second thread, we use the main thread to run ui related activities
        dispatch_async(dispatch_get_main_queue(),^{
            [spinner stopAnimating];
                ViewController *controller = [[ViewController alloc] initWithNibName:@"ViewController" array:array];
                [self.navigationController pushViewController:controller animated:YES];
                [controller release];                    
        });
    });
    dispatch_release(download_queue);    


No comments: