0

当我像这样使用它时,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];
4

2 回答 2

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

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

于 2012-11-29T06:54:20.260 回答
0

你可以像这样得到NSTimer的点地址

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

并将其用于另一种方法。

于 2012-11-29T07:24:10.680 回答