首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >线程和NSTimer的问题

线程和NSTimer的问题
EN

Stack Overflow用户
提问于 2010-07-26 21:16:58
回答 3查看 2.8K关注 0票数 0

我的代码中有一个问题。我想启动线程,但是当线程启动时,它们不能启动NSTimer指令。你能帮帮我吗?

代码语言:javascript
复制
-(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]]; 

        }
}
EN

回答 3

Stack Overflow用户

发布于 2010-07-26 22:55:53

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

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

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

另请参阅:

Running NSTimer Within an NSThread?

Threaded NSTimer

票数 1
EN

Stack Overflow用户

发布于 2011-04-14 18:33:35

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

代码语言:javascript
复制
[self performSelectorOnMainThread:@selector(startTimer) withObject:nil waitUntilDone:FALSE]; 

希望这篇文章能帮助你

票数 1
EN

Stack Overflow用户

发布于 2010-07-26 22:45:17

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3335114

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档