gpt4 book ai didi

cocoa - 更改重复计时器的 NSTimer 间隔

转载 作者:行者123 更新时间:2023-12-03 16:11:59 28 4
gpt4 key购买 nike

我正在 Cocoa 中使用如下设置的 NSTimer 运行 mainLoop:

        mainLoopTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/fps target:self selector:@selector(mainloop) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:mainLoopTimer forMode:NSEventTrackingRunLoopMode];

在程序启动时,我将 timeInterval 设置为 0.0,以便主循环尽可能快地运行。无论如何,我想提供一个函数来在运行时将帧速率(以及计时器的时间间隔)设置为特定值。不幸的是,据我所知,这意味着我必须重新初始化计时器,因为 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];
}

但这会引发以下错误并停止主循环:

2010-06-09 11:14:15.868 myTarget[7313:a0f] setFrameRate 2010-06-09 11:14:15.868 myTarget[7313:a0f] * __NSAutoreleaseNoPool(): Object 0x40cd80 of class __NSCFDate autoreleased with no pool in place - just leaking 2010-06-09 11:14:15.869 myTarget[7313:a0f] * __NSAutoreleaseNoPool(): Object 0x40e700 of class NSCFTimer autoreleased with no pool in place - just leaking 0.614628

我还尝试使用“retain”关键字重新创建计时器,但这并没有改变任何东西。关于如何在运行时动态更改 NSTimer 的间隔有什么想法吗?

谢谢!

最佳答案

我知道,这个帖子太老了!但我也在寻找该功能!

事实证明,NSTimes 不提供此功能,我决定构建一个自己的功能。这不是最好的解决方案,但就我而言,这是唯一可能的。

我定义了变量“BOOL keepOn;”在我的标题中。

-(IBAction)doSomething:(id)sender
{
// Any action to throw every interval.
}

-(IBAction)switchAutoLoad:(id)sender
{
if([autoLoad state] == NSOffState)
{
NSLog(@"auto-reload on!");

self performSelector:@selector(fireTimer) withObject:nil afterDelay:0];
keepOn = YES;
[autoLoad setState:NSOnState];
}
else
{
NSLog(@"auto-reload off!");
keepOn = NO;
[autoLoad setState:NSOffState];
}
}

-(void)fireTimer
{
[self doSomething:nil];

float theTime = 20; // This is the time interval.

if(keepOn)
{
[self performSelector:@selector(fireTimer) withObject:nil afterDelay:theTime];
}
}

(非常)之二的问题是,“计时器”在获得新值之前正在等待整个延迟。你看,它的响应速度并不快:))而且你不能立即停止它(必须等待延迟完成)。

如果你停止它,它会按照预期再执行一个操作。

实际上它适用于我的应用程序和工具。

关于cocoa - 更改重复计时器的 NSTimer 间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3004569/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com