ios - 用NSTimer替换usleep吗?

标签 ios objective-c nstimer

在下面的代码中,如何用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

最佳答案

您不能。 这两个完全不同,此代码需要阻止操作。编辑:因为它是在后台线程上执行的。
-progressTask:方法是从this method执行的new thread执行的:

- (void)launchExecution {
    @autoreleasepool {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        // Start executing the requested task
        [targetForExecution performSelector:methodForExecution withObject:objectForExecution];
#pragma clang diagnostic pop
        // Task completed, update view in main thread (note: view operations should
        // be done only in the main thread)
        [self performSelectorOnMainThread:@selector(cleanUp) withObject:nil waitUntilDone:NO];
    }
}

它依赖于同步执行,使用NSTimer会要求启动NSRunLoop并使其运行一段时间,这实际上是可能的,但是只是不使用

提示:如果您更喜欢Objective-C方法,请在几秒钟内用参数调用+[NSThread sleepForTimeInterval:]

关于ios - 用NSTimer替换usleep吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29975663/

相关文章:

IOS 应用程序每 30 秒发送一次请求

ios - UIWebview中如何获取当前播放视频的url

ios - 将标签栏嵌入到 iPhone 屏幕顶部

ios - 调用 UIApplication 子类方法启动 scheduledTimer

ios - 拆除 UITableViewDataSource

objective-c - AsyncSocket:如何定义读取长度并仅在达到读取长度时获得回调

iphone - 使用 NSTimer 的序列动画

iphone - 如何在 iPhone 中显示在应用程序启动时向下滚动的介绍屏幕?

ios - Safari 书签管理器背后可能的 View Controller 设计是什么?

ios - 如何从 iOS 8 照片框架中的 PHAsset 获取城市名称、省、州?