本文介绍了NSThread,NSTimer和AutoreleasePools的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在iPhone中创建一个应用程序,其中我想使用NSThread。我已使用

I want to create an appilication in iPhone in which I want to use NSThread. I have created one thread using

[NSThread detachNewThreadSelector:@selector(doThread:)
                             toTarget:self
                           withObject:nil];



我希望我的一个线程将处理所有的触摸和其他用户交互,第二个线程处理NSTimer。所以,在doThread()我已经分配NSTimer喜欢,

I want that my one thread will handle all the touches and other user interaction and the second thread handle the NSTimer. So, In doThread() I have allocate NSTimer like,

-(void) doThread:(NSString *)poststring {

    NSLog(@"create thread:");

    [lock lock];
    T1 = [NSTimer scheduledTimerWithTimeInterval:(5)            
     target : self
     selector:@selector(onTimer)
     userInfo : nil
     repeats : YES];
     NSLog(@"after timer");

    usleep(1);
    [lock unlock];
}

In onTImer,

-(void)onTimer

{
    NSLog(@"in timer");

}

现在我不能调用onTimer方法NSTimer。但我可以看到后定时器打印在日志中。我不能在线程中使用NSTimer的任何东西?

Now I can't able to call the onTimer method of NSTimer. But I can see the "after timer" printed in the log.Is that anything that I can't use the NSTimer within the thread?

这也是我可以得到同时执行。

This is also I can get while execution.

NSAutoreleaseNoPool(): Object 0xd15880 of class __NSCFDate autoreleased with no pool in place - just leaking
Stack: (0x305a2e6f 0x30504682 0x30525acf 0x27b5 0x3050a79d 0x3050a338 0x926ae155 0x926ae012)

请帮助我。
谢谢。

Please help me for that.Thank you.

推荐答案

NSTimer 对当前 NSRunLoop - 你的线程不启动一个。

NSTimer schedules its time events on the current NSRunLoop--your thread doesn't start one.

如果你想做的是在一定时间后运行一些东西,使用 - [NSObject performSelector:withObject:afterDelay:]

If all you are trying to do is run something after a certain amount of time, use -[NSObject performSelector:withObject:afterDelay:]:

[self performSelector:@selector(onTimer) withObject:nil afterDelay:5.0f];

如果你想在后台实际工作, + [NSThread detachNewThreadSelector:toTarget:withObject:] 将按预期工作,但您不应在后台运行计时器事件,而不使用 NSRunLoop 。此外,您需要将代码包装在自动释放池中:

If you are trying to actually do work in the background, +[NSThread detachNewThreadSelector:toTarget:withObject:] will work as expected but you shouldn't run timer events in the background without an NSRunLoop. Also, you will need to wrap your code in an autorelease pool:

- (void)doThread:(NSString *)poststring
{
     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
     // Your code goes in here
     [pool drain];
}

这篇关于NSThread,NSTimer和AutoreleasePools的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 01:50