Reputation: 79
I have a problem when reloading the table after downloading the data in JSON format.
Use the NSOperation to download data async.
The code that i use it's this
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadInformactionToSql];
}
-(void)loadInformactionToSql {
NSOperationQueue * queue = [NSOperationQueue new];
NSInvocationOperation * operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(downloadJSONBDD) object:nil];
[queue addOperation:operation];
}
-(void)downloadJSONBDD {
NSURL * url = [NSURL URLWithString:@"http://judokatium.com/index.php/api/Belts/getBeltsWithTechnicals"];
//Leer el JSON
NSData * allCinturonesTecnicasJson =
[[NSData alloc] initWithContentsOfURL:url];
NSError *error;
NSArray * allCinturonesJson =
[NSJSONSerialization JSONObjectWithData:allCinturonesTecnicasJson options:kNilOptions error:&error];
if(error) {
NSLog(@"%@, %@", [error localizedDescription], [error localizedFailureReason]);
} else {
NSDictionary * cintns;
cinturones = [[NSMutableArray alloc] init];
for(int i = 0; i < [allCinturonesJson count]; i++){
JLMCinturon * cinturon = [[JLMCinturon alloc] init];
cintns = [allCinturonesJson objectAtIndex:i];
cinturon.idCinturon = [cintns objectForKey:@"id"];
[cinturones addObject:cinturon];
}
[self.tablaCinturones reloadData];
self.tablaCinturones.hidden = NO;
}
}
The downloaded data are correct, but not shown in the table.
How can i fix it?
Thanks and Sorry for my bad english.
Upvotes: 0
Views: 73
Reputation: 5745
Put these lines
[self.tablaCinturones reloadData];
self.tablaCinturones.hidden = NO;
into a dispatch block that moves them to the main thread
dispatch_async(dispatch_get_main_queue(), ^{
[self.tablaCinturones reloadData];
self.tablaCinturones.hidden = NO;
});
The problem is that NSOperation
moves your method calls to a different thread, and the UI cannot be updated in iOS from any thread but the main one.
Or, you could use NSOperation
as you already have and as @JulianKról pointed out.
NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
NSInvocationOperation *reloadOperation = [[NSInvocationOperation alloc] initWithTarget:self.tablaCinturones selector:@selector(reloadData) object:nil];
NSInvocationOperation *hiddenOperation = [[NSInvocationOperation alloc] initWithTarget:self.tablaCinturones selector:@selector(setHidden:) object:@(NO)];
[mainQueue addOperation:reloadOperation];
[mainQueue addOperation:hiddenOperation];
Upvotes: 3