我的代碼有問題。 我想啓動線程,但啓動時它們不能啓動NSTimer構造。 你能幫我嗎?線程和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]];
}
}
不完全正確。計劃的計時器被隱式保留。沒有必要保留它。你的第二個想法可能是正確的。 – tonklon 2010-07-26 14:48:46
它是在從類方法返回對象之前將對象添加到當前自動釋放緩衝池的概念。 案例對象'pool'是當前線程退出之前釋放的自動釋放池。所以當「池」被釋放它裏面的所有對象會得到釋放消息 - 所以保留了對象,你應該1. – 2010-07-26 15:00:29
我用一個示例程序做了詳細的研究,一些意見 1.定時器增加保留計數在它創建的同一個運行循環中觸發,每個線程都有自己的運行循環,所以你的線程應該運行,讓你的計時器在你提到的時間觸發。 2. scheduledTimerWithTimeInterval返回與保留計數爲對象的NSTimer「2」那麼,當自動釋放池被釋放,一旦定時事件被觸發第二個將被降低一個數量將會減少。 – 2010-07-26 18:04:57