Nitish
Nitish

Reputation: 14123

UITableView reloaded before NSoperationQueue starts

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];

}  

Upvotes: 0

Views: 484

Answers (3)

Alex Terente
Alex Terente

Reputation: 12036

You have to set a completion bloc for your NSOperation. Where you have to call reload data on your table view.

- (void)setCompletionBlock:(void (^)(void))block

Edit:

add this

[obj setCompletionBlock:^{
                                NSLog(@"I have fnish");
                                 [self.tableView reloadData];
                                } 
     ]; 

Upvotes: 1

viggio24
viggio24

Reputation: 12366

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).

Upvotes: 1

fannheyward
fannheyward

Reputation: 19327

Call [tableView reloadData] after the operationQueue finished.

Upvotes: 0

Related Questions