0

我的代码有问题。我想启动线程,但是当它启动时,他们无法启动 NSTimer 指令。你能帮助我吗?

-(void)detectionMove:(NSTimer*)timer{

    int indexArray = [[[timer userInfo] objectForKey:@"arrayIndex"] intValue];
    // do something
}



-(void)callDectectionMove:(NSNumber*)arrayIndex{

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init]; 

    NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] init];  
    [myDictionary setObject:arrayIndex forKey:@"arrayIndex"];  

    //This istruction can't lunch a detectionMove method
    [NSTimer scheduledTimerWithTimeInterval:timeToCatch target:self selector:@selector(detectionMove:) userInfo:myDictionary repeats:NO];   

    [pool   release]; 

}


-(void)detectPositionMovement{


    for(int i = 0; i< [self.arrayMovement count]; i++){

        if((actualAccelerometerX+sensibilityMovement) > [[[[self.arrayMovement      objectAtIndex:i] arrayPositionMove]objectAtIndex:0] valueX] && (actualAccelerometerX-sensibilityMovement) < [[[[self.arrayMovement      objectAtIndex:i] arrayPositionMove]objectAtIndex:0] valueX] &&
           (actualAccelerometerY+sensibilityMovement) > [[[[self.arrayMovement      objectAtIndex:i] arrayPositionMove]objectAtIndex:0] valueY] && (actualAccelerometerY-sensibilityMovement) < [[[[self.arrayMovement      objectAtIndex:i] arrayPositionMove]objectAtIndex:0] valueY] &&
           (actualAccelerometerZ+sensibilityMovement) > [[[[self.arrayMovement      objectAtIndex:i] arrayPositionMove]objectAtIndex:0] valueZ] && (actualAccelerometerZ-sensibilityMovement) < [[[[self.arrayMovement      objectAtIndex:i] arrayPositionMove]objectAtIndex:0] valueZ])
            [NSThread detachNewThreadSelector:@selector(callDectectionMove:) toTarget:self withObject:[NSNumber numberWithInt:(int)i]]; 

        }
}
4

3 回答 3

1

你真的,真的需要一个不同的线程吗?你想在那个后台线程上启动定时器,为什么不能在主线程上启动定时器呢?

回答您的问题:第一个问题是:您的线程没有像 Girish 建议的那样运行足够长的时间。

第二个问题是:您没有循环线程的运行循环。计时器需要运行循环才能工作。

也可以看看:

在 NSThread 中运行 NSTimer?

线程化的 NSTimer

于 2010-07-26T14:55:53.143 回答
1

刚刚解决!关键是在主线程中启动定时器

[self performSelectorOnMainThread:@selector(startTimer) withObject:nil waitUntilDone:FALSE]; 

希望这能帮助

于 2011-04-14T10:33:34.740 回答
0

您正在威胁中创建 NSTimer 并将计时器对象添加到池中(因为它是类方法),因此在您的计时器被调用之前,计时器对象将被释放(因为线程上下文将在计时器被触发之前结束)。

有 2 个解决方案 1. 将保留计数添加到 NSTimer 对象并在完成计时器工作后释放。2. 确保在计时器完成其工作之前您的线程不会退出。

于 2010-07-26T14:45:17.393 回答