I have a problem calculating progress for my UIProgressView. My float value has no effect on the progress. I tried to set progress manually it works fine but if I try to calculate it it doesn't work.
Here is my code :
- (void) initProgressbar {
self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
[self.progressView setFrame:CGRectMake(0, 0, SCREEN_WIDTH / 2, 10)];
self.progressView.center = CGPointMake(SCREEN_WIDTH - 110, SCREEN_HEIGHT - 25);
self.progressView.progress = 0.0;
[self.view addSubview:self.progressView];
}
nbElementsSync
and nbElementsToSync
are global int properties and nbElementsSync
is incremented by a loop before updateProgress
method is being called.
MyController.h
@interface MyController : UIViewController {
NSString *json;
int nbElementsToSync;
int nbElementsSync;
}
@property (nonatomic, strong) UIProgressView *progressView;
MyController.m
nbElementsSync = 0; // Nb elements synchronized
nbElementsToSync = [[json valueForKey:@"count"] intValue]; // Nb elements to synchronize
for (NSString* result in results) {
nbElementsSync++;
[self updateProgress];
}
And here is my method to set up the progress :
- (void) updateProgress {
[self.progressView setProgress:((float)nbElementsSync / nbElementsToSync)];
NSLog(@"percent : %f", ((float)nbElementsSync / nbElementsToSync));
}
Results of my NSLog :
percent : 0.003937
percent : 0.007874
percent : 0.011811
percent : 0.015748
percent : 0.019685
percent : 0.023622
...
Any idea to solve it ? Thanks in advance.
Have you tried doing the loop in a background process, not to block the UI updates :
MyController.m
Call this where you need to:
[self performSelectorInBackground:@selector(syncInBackground) withObject:nil];
Then
- (void)syncInBackground
{
int nbElementsSync = 0; // Nb elements synchronized
int nbElementsToSync = [[json valueForKey:@"count"] intValue]; // Nb elements to synchronize
for (NSString* result in results) {
nbElementsSync++;
float percent = (float)nbElementsSync / nbElementsToSync;
[self performSelectorOnMainThread:@selector(updateProgress:) withObject:[NSNumber numberWithFloat:percent] waitUntilDone:NO];
}
}
- (void) updateProgress:(NSNumber *)percent {
[self.progressView setProgress:percent.floatValue];
}