I am using NSOperationQueue
for calling a service in background in viewWillAppear
(I also tried putting it in viewDidLoad
for that matter). I am populating the UITableView
based on results I get from service. When I debug the application, the table gets called first and then the operationQueue. In this way the table is empty for me. How to populate the table after operationQueue does its job.
Here is the code :
viewWillAppear :
-(void)viewWillAppear:(BOOL)animated
{
operationQueue=[[NSOperationQueue alloc] init];
ParseOperation *obj=[[ParseOperation alloc] initWithMembers:ID];
[operationQueue addOperation:obj];
[obj release];
}
You can add the "reloadTable" as a specific operation with dependency on the parse operation, immediately after the parse operation definition and just before starting the queue (so for safety initialize the queue as suspended and then start it only once all operations have been added):
// ... inside your operation code definition
NSInvocationOperation *reloadOp = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(myReload) object:nil];
[reloadOp addDependency:obj] // adding here the parse operation as a dependency
[operationQueue addOperation:reloadOp];
The "myReload" operation needs to be defined as a stand-alone method in order to ensure that the reloadTable method is called in the main thread:
-(void)myReload {
[table performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
}
In this way your reload code will be run only after the parse operation terminates. This is useful if you have more operations to be run and all them needs to be executed before the table reload. Note that the dependency is unaware of the fact that the operation terminated normally or has been cancelled.
Another good way you may consider is to define a GCD serial queue and add the two blocks in sequence (first block is parsing, second block is table reload). In such case GCD will guarantee the proper execution order of the two blocks (FIFO).