【问题标题】:NSTimer not working when used in different functionsNSTimer 在不同的功能中使用时不起作用
【发布时间】:2012-11-29 06:35:40
【问题描述】:

当我像这样使用 ns 计时器时,它会同时调用 foo1 和 foo1

-(void)register1
{
    NSRunLoop * runLoop = [NSRunLoop currentRunLoop];
    [runLoop addTimer:[NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(foo) userInfo:nil repeats:YES] forMode:NSDefaultRunLoopMode];
     [runLoop addTimer:[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(foo2) userInfo:nil repeats:YES] forMode:NSDefaultRunLoopMode];
    [runLoop run];
}

但我的要求是我必须在不同的函数中使用 nstimer,以便我可以创建两者的 nsoperation。下面的代码只调用第一个函数。即,当我从 main 调用 register1 和 register2 时,只注册了一个计时器。第一名

-(void)register1
{
    NSRunLoop * runLoop = [NSRunLoop currentRunLoop];
    [runLoop addTimer:[NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(foo) userInfo:nil repeats:YES] forMode:NSDefaultRunLoopMode];

    [runLoop run];
}
-(void)register2
{

    NSRunLoop * runLoop = [NSRunLoop currentRunLoop];
    [runLoop addTimer:[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(foo2) userInfo:nil repeats:YES] forMode:NSDefaultRunLoopMode];
    [runLoop run];
}

我已经找到了我的问题的答案,我想我也应该告诉其他人。解决方案是我必须为每个函数使用不同的线程。我以这种方式在 main 中使用了 nsoperation

abc *ab=[[abc alloc]init];
//[ab register1];
  //  [ab register2];


    NSOperationQueue *queue=[[NSOperationQueue alloc]init];
    NSInvocationOperation *abc=[[NSInvocationOperation alloc]initWithTarget:ab selector:@selector(register1) object:(nil)];
    NSInvocationOperation *abc2=[[NSInvocationOperation alloc]initWithTarget:ab selector:@selector(register2) object:(nil)];
   [queue addOperation:abc];
    [queue addOperation:abc2];

【问题讨论】:

  • 你试过扩大runLoop的范围吗?我担心它会在你用完之前被处理掉。

标签: objective-c nstimer nsoperation


【解决方案1】:
  1. 当你使用+[NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:] 时不要调用-[NSRunLoop addTimer:forMode:] - 这是多余的。名称中的 scheduled 部分说明了一切:它正在为您创建一个已在当前运行循环中安排好的计时器。
  2. 一般不要打电话给-[NSRunLoop run]。它无限期地运行runloop。它基本上永远不会回来。所以你的第二个函数实际上并没有被调用,因为你永远不会从你的第一个函数返回。您可以通过在不同位置插入 NSLog 语句或在调试器中单步执行您的代码来轻松确认这一点。

如果您发布更多代码(尤其是您的 main() 函数),那么我们可以为您提供更多答案。通常,您只想从 main() 调用 -[NSRunLoop run](或其变体)。

【讨论】:

    【解决方案2】:

    你可以这样获取NSTimer的点地址

    NSTimer NSTimer * aTimer = [NSTimer scheduledTimerWithTimeInterval:10 target:self 选择器:@selector(foo) userInfo:nil repeats:YES] forMode:NSDefaultRunLoopMode];

    并将其用于另一种方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-06
      • 2016-10-29
      • 2012-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-03
      相关资源
      最近更新 更多