1 iphone cocoa multithreading timer objective-c
我想在iPhone中创建一个我想使用NSThread的appilication.我用了创建了一个线程
[NSThread detachNewThreadSelector:@selector(doThread:)
toTarget:self
withObject:nil];
Run Code Online (Sandbox Code Playgroud)
我希望我的一个线程将处理所有的触摸和其他用户交互,第二个线程处理NSTimer.所以,在doThread()中,我已经分配了NSTimer,
-(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");
}
Run Code Online (Sandbox Code Playgroud)
现在我无法调用NSTimer的onTimer方法.但我可以看到日志中打印出"after timer".是不是我在线程中无法使用NSTimer?
这也是我执行时可以得到的.
NSAutoreleaseNoPool(): Object 0xd15880 of class __NSCFDate autoreleased with no pool in place - just leaking
Stack: (0x305a2e6f 0x30504682 0x30525acf 0x27b5 0x3050a79d 0x3050a338 0x926ae155 0x926ae012)
Run Code Online (Sandbox Code Playgroud)
请帮助我.谢谢.
NSTimer在当前NSRunLoop线程上安排其时间事件 - 您的线程不会启动它.
如果您要做的只是在一段时间后运行某些东西,请使用-[NSObject performSelector:withObject:afterDelay:]:
[self performSelector:@selector(onTimer) withObject:nil afterDelay:5.0f];
Run Code Online (Sandbox Code Playgroud)
如果您尝试在后台实际工作,+[NSThread detachNewThreadSelector:toTarget:withObject:]将按预期工作,但您不应在没有的情况下在后台运行计时器事件NSRunLoop.此外,您需要将代码包装在自动释放池中:
- (void)doThread:(NSString *)poststring
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Your code goes in here
[pool drain];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4610 次 |
| 最近记录: |