【问题标题】:NSTimer starts after the method which is called after it finishesNSTimer 在完成后调用的方法之后启动
【发布时间】:2012-10-21 13:50:30
【问题描述】:

我正在使用 NSTimer 更新 UIProgressView,以便每秒进度增加 0.1。

-(void)updateBar{
     NSLog(@"Increase by 0.1");
     pbar.progress=pbar.progress+0.1;
 }

 -(void)foo{
    NSLog("START Foo");
    //Does some stuff that takes about 10sec
    NSLog("FINISH Foo");
 }

 -(void) viewDidLoad{
     pbar = [[UIProgressView alloc] initWithFrame:CGRectMake(-280, 500, 730, 90)];
     pbar.progressViewStyle = UIProgressViewStyleDefault;
     pbar.progressTintColor = [UIColor colorWithRed:68.0/255 green:186.0/255 blue:41.0/255 alpha:1.0];
     pbar.progress = 0.0;
     pbar.transform = CGAffineTransformMakeRotation(90 * M_PI / 180.0);
     [self.view addSubview:pbar];

     [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(updateBar) userInfo:nil repeats: YES];

     [self foo];
 }

所以理想情况下,UIProgressView 的进度会在 foo 方法运行期间增加。但是,计时器在 foo 方法完成后启动,所以我的控制台最终看起来像这样......

START Foo
FINISH Foo
Increase by 0.1
Increase by 0.1
Increase by 0.1
And so on ....

知道为什么会发生这种情况吗?更重要的是,我如何让它做我想做的事情并让计时器在 foo 被调用之前开始运行。

【问题讨论】:

  • 你可以在-foo的开头调用-updateBar

标签: objective-c multithreading nstimer


【解决方案1】:

- (void) updateBar 方法在运行循环中被延迟,而- (void) foo 被立即执行。

当您实现代码时,您缺少一个对NSTimer 的引用(特别是一个实例变量),您将使用它来结束计时器。

您将使用- (void) foo 方法末尾的变量来停止计时器。

【讨论】:

    【解决方案2】:

    您正在调用的特定方法“scheduledTimerWithTimeInterval”在 current 运行循环中运行计时器,这解释了为什么“foo”在计时器触发之前执行它。

    如果您想在单独的(后台)线程上运行,为什么不创建和分离线程 (or blocks, here's a related question that might help you out),然后在单独的线程上运行相同的调用。当然,如果你正在做任何与 UI 相关的事情,你必须在主线程上进行实际的 UI 更新。因此,虽然计时器在单独的线程上运行,但在主线程上执行实际的 UI 操作(通过类似“performSelectorOnMainThread:”的方式)。

    【讨论】:

    • 好的,谢谢,所以我最终使用了performSelectorInBackground:,并让它做我想做的事,但是我使用performSelectorOnMainThread: 调用updateBar,因为我希望它改变用户界面和这不起作用,因为 UI 更改要等到 foo 完成才会出现。
    猜你喜欢
    • 1970-01-01
    • 2019-09-26
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多