如何在以下代码中将usleep
替换为NSTimer
:
/**
* DETERMINATE BAR with LABEL
*/
- (void)showDeterminateBarWithLabel:(CDVInvokedUrlCommand *)command {
// obtain commands
bool dim = [[command.arguments objectAtIndex:0] boolValue];
int increment = [[command.arguments objectAtIndex:1] intValue];
NSNumber* incrementValue = @(increment);
NSString* text = [command.arguments objectAtIndex:2];
// initialize indicator with options, text, detail
self.progressIndicator = nil;
self.progressIndicator = [MBProgressHUD showHUDAddedTo:self.webView.superview animated:YES];
self.progressIndicator.mode = MBProgressHUDModeDeterminateHorizontalBar;
self.progressIndicator.labelText = text;
// Check for dim : true ? false
if (dim == true) {
self.progressIndicator.dimBackground = YES;
}
// Load Progress bar with ::incrementValue
[self.progressIndicator showWhileExecuting:@selector(progressTask:) onTarget:self withObject:incrementValue animated:YES];
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@""];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (void)progressTask:(NSNumber *)increment{
// get increment value
int _increment = [increment intValue];
float progress = 0.0f;
while (progress < 1.0f) {
progress += 0.01f;
self.progressIndicator.progress = progress;
// increment in microseconds (100000mms = 1s)
usleep(_increment);
}
}
此代码取自here。
答案 0 :(得分:2)
简而言之,您无法使用阻止线程。使用任何类型的睡眠或延迟来阻塞线程是一种糟糕的设计,应该在极少数情况下避免使用。
严禁在iOS / OS X应用程序中阻止主线程。必须允许主runloop运行,否则你的应用程序最多会没有响应,最坏的情况是不行。
相反,使用NSTimer定期回调代码以更新值。它不会阻止执行。