我正在使用NSTimer设置在Cocoa中运行mainLoop,如下所示:
mainLoopTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/fps target:self selector:@selector(mainloop) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:mainLoopTimer forMode:NSEventTrackingRunLoopMode];
Run Code Online (Sandbox Code Playgroud)
在程序启动时,我将timeInterval设置为0.0,以便mainloop尽可能快地运行.无论如何,我想提供一个函数来在运行时将帧速率(以及计时器的时间间隔)设置为特定值.不幸的是,据我所知,这意味着我必须重新初始化计时器,因为Cocoa不提供像"setTimerInterval"这样的函数这是我试过的:
- (void)setFrameRate:(float)aFps
{
NSLog(@"setFrameRate");
[mainLoopTimer invalidate];
mainLoopTimer = nil;
mainLoopTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/aFps target:self selector:@selector(mainloop) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:mainLoopTimer forMode:NSEventTrackingRunLoopMode];
}
Run Code Online (Sandbox Code Playgroud)
但是这会引发以下错误并停止主循环:
2010-06-09 11:14:15.868 myTarget [7313:a0f] setFrameRate 2010-06-09 11:14:15.868 myTarget [7313:a0f] *__NSAutoreleaseNoPool():类__NSCFDate的对象0x40cd80自动释放,没有池到位 -只是泄漏2010-06-09 11:14:15.869 myTarget [7313:a0f]* __NSAutoreleaseNoPool():类NSCFTimer的对象0x40e700自动释放,没有池到位 - 只是泄漏0.614628
我还尝试使用"retain"关键字重新创建计时器,但这并没有改变任何东西.有关如何在运行时动态更改NSTimer间隔的任何想法?
谢谢!
您不应该释放 mainLoopTimer。
当您创建它时,您收到了一个自动释放的实例,并且运行循环保留对该实例的引用。
当您将其从循环中删除时,它将被释放:如果您手动释放它,它将被删除,并且运行循环会尝试访问无效对象。
这就是它崩溃的原因。
编辑:我完全误读了,我以为我看到发布时它是无效的,抱歉。问题似乎是没有 AutoreleasePool 到位。这通常在 main() 中完成:首先创建自动释放池
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Run Code Online (Sandbox Code Playgroud)
并在退出 main 之前释放它。
请查看此处的自动释放池文档。
| 归档时间: |
|
| 查看次数: |
6723 次 |
| 最近记录: |