开发者

Problem with Thread and NSTimer

I have a problem in my code. I want to launch the thread but when it is launched they can't start a NSTimer istruction. Can you help me?

-(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]]; 

        }
}


Do you really, really need a different Thread? You want to start a timer on that background Thread, why can't you start the timer on the main thread?

To answer your question: The fist problem is: Your Thread does not run long enough like Girish suggested.

The second problem is: You are not looping the Thread's runloop. A runloop is needed for a timer to work.

See also:

Running NSTimer Within an NSThread?

Threaded NSTimer


Just solved! The key is starting the timer in the main thread

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

Hope this hepls


You are creating NSTimer in the threat and timer object is added to pool(since it is class method), so before your timer is getting called the timer object will be released(since thread context will be over before timer is fired).

There are 2 solution 1. Add a retain count to the NSTimer object and release once you done with timer work. 2. Make sure your thread is not exited until timer is done its work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜