NSThread的问题

时间:2010-07-27 10:06:18

标签: iphone objective-c nsthread

我的代码有问题 我想用NSThread创建2个不同的实例,但我认为在我的问题中这些都不会发生。 你能解决我的问题吗? 我发布了我的代码,如果可以,你可以展示一个解决方案的例子吗? 谢谢

@implementation myClass


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

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

    identificationMove *identifier = [[identificationMove alloc]init];
    [identifier setArrayIndex:(NSNumber*)arrayIndex];
    [identifier detectionMove];

    [identifier release];

}


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

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

    [self performSelectorOnMainThread:@selector(detectMove:) withObject:(NSNumber*)arrayIndex waitUntilDone: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])

                    //I'm not sure that these istruction can start a 2 different and indipendent thread
            [NSThread detachNewThreadSelector:@selector(callDectectionMove:) toTarget:self withObject:[NSNumber numberWithInt:(int)i]];  

        }
}

@end

3 个答案:

答案 0 :(得分:2)

在你的代码中[self.arrayMovement count]将创建线程数,但它们将按顺序运行,因为所有线程都想在主线程中执行'detectMove'函数。

执行以下语句时:

[self performSelectorOnMainThread:@selector(detectMove:) withObject:(NSNumber*)arrayIndex waitUntilDone:NO];

- &GT; make方法'detectMove'在主线程中执行,一个线程一次只能执行一个语句,因此你将看到线程实现的顺序操作。

答案 1 :(得分:0)

最终,detectMove方法在主线程中执行 我相信detectPositionMovement也是从主线程执行的 因此,在detectMove完成之前,任何detectPositionMovement的执行都不会开始。

尝试直接从detectMove致电detectPositionMovement(不使用callDectectionMove而不使用performSelectorOnMainThread)。

答案 2 :(得分:0)

将断点放在detectPositionMovement中,然后检查此行的执行次数:

[NSThread detachNewThreadSelector:@selector(callDectectionMove:) toTarget:self withObject:[NSNumber numberWithInt:(int)i]];

如果正在执行2次,则会调度两个线程。如果没有,则检查“if”块中的条件。