Search code examples
iphonexcodeconditional-statementsmbprogresshud

MBProgressHUD Conditional execution


I have a tableview whose contents are generated with json array. It also employes location services so as users' location changes, the table is reloaded to reflect the changes of the table data relative to users' location.

My problem is I show the activity indicator in the beginning of the view load, but each time location updates and table reloads, the indicator is shown. This is done in very short intervals, causing the application to crash.

Is it possible to put a condition to following code so that it wonT show MBProgressHUD if it is not the initial load but it is there reload caused by the location changes?

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    [self.navigationController.view addSubview:HUD];
    [HUD showWhileExecuting:@selector(myTask) onTarget:self withObject:nil animated:YES];
    return [rows count];
}

This is where the reload is performed:

    - (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{

    NSString *lat = [NSString stringWithFormat:@"%f", newLocation.coordinate.latitude];

    NSString *longt = [NSString stringWithFormat:@"%f", newLocation.coordinate.longitude];

    //CGFloat Alat = [lat floatValue];
    //CGFloat Alon = [longt floatValue];
    self.aalat = lat;
    self.aalon = longt;
    //        NSLog(@"anlat: %@", aalat);
    //        NSLog(@"anlong: %@", aalon);
    [[NSUserDefaults standardUserDefaults] setObject:aalat forKey:@"latitude"];
    [[NSUserDefaults standardUserDefaults] setObject:aalon forKey:@"longitude"]; 
    [tableview reloadData];
}

Solution

  • I would trigger the HUD from your viewDidLoad or viewWillAppear methods to load things up initially. Firing from the tableview is going to give you lots of problems. The tableview methods are fired repeatedly when the user scrolls, so you will always have issues with that going on.

    Fire a method from your location update to display the HUD. It has to run on the main thread anyway for the animations to work correctly. I would call the reload table from your new method to avoid any issues with your tableview.