我的代码中有一个问题。我想启动线程,但是当线程启动时,它们不能启动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]];
}
}发布于 2010-07-26 22:55:53
你真的,真的需要一个不同的线程吗?你想在后台线程上启动计时器,为什么不能在主线程上启动计时器呢?
回答你的问题:第一个问题是:你的线程没有像Girish建议的那样运行足够长的时间。
第二个问题是:你没有循环Thread的runloop。计时器需要运行循环才能工作。
另请参阅:
发布于 2011-04-14 18:33:35
刚刚解决了!关键是在主线程中启动计时器
[self performSelectorOnMainThread:@selector(startTimer) withObject:nil waitUntilDone:FALSE]; 希望这篇文章能帮助你
发布于 2010-07-26 22:45:17
您在threat中创建了NSTimer,并将timer对象添加到池中(因为它是类方法),因此在调用timer之前,timer对象将被释放(因为线程上下文将在timer被触发之前结束)。
有两种解决方案1.向NSTimer对象添加一个保留计数,并在完成计时器工作后释放。2.确保您的线程在timer完成其工作之前不会退出。
https://stackoverflow.com/questions/3335114
复制相似问题