ios - NSTimer 更改间隔性能

标签 ios objective-c performance nstimer

我的应用程序使用 NSTimer 以固定间隔(亚秒)将自定义 SKNode 对象添加到 SKScene。在某些时候,我希望计时器加速。这是我所做的(代码简化):

@interface MyScene : SKScene
@end

@implementation MyScene {
    MyNode *node;
    NSTimer *timer;
    int speed;
}

- (id):initWithSize:(CGSize)size {
    if (self = [super initWithSize:size]) {
        speed = 0.8f;
        timer = [NSTimer = scheduledTimerWithTimeInterval:speed target:self selector:@selector(addNodeToScene) userInfo:nil repeats:YES];
    }
}

- (id):addNodeToScene {
    if (node != nil) {
        [node removeFromParent];
        node = nil;
    }

    CGPoint location = //random x y coordinates using arc4random()...

    node = [[MyNode alloc] initAtLocation:location];
    [self addChild:node];
}

// at some point I call this method (called regularly throughout life of app)
- (id):speedUp {
    [timer invalidate];
    timer = nil;
    speed *= 0.9f;
    timer = [NSTimer = scheduledTimerWithTimeInterval:speed target:self selector:@selector(addNodeToScene) userInfo:nil repeats:YES];
}

我注意到每次调用 speedUp 时都会有轻微的延迟。我是 Objective-C 的新手,所以不确定如何解决。在计时器上使用调度队列是否更有效,还是我不能避免这个问题,因为内部速度太快了?

我在仪器上运行时间分析,但没有突出显示 - 相反,我最重要的方法是 addNodeToScene

最佳答案

我的猜测是您在 -addNodeToScene 的正常工作之外调用了 -speedUp。如果是这样,延迟很可能是因为您已经用完了之前的一些延迟,然后 -speedUp 使旧计时器无效并创建一个新计时器,这将启动所有延迟再次。每当您比上一个计时器触发超过 10% 时,您都会看到延迟。

我将尝试一些 ASCII 艺术来说明。 + 是计时器触发,* 是当您调用 -speedUp 并重置计时器时。

+---------+--------+---------+---------+---------+
+---------+---*--------+--------+--------+--------+

关于ios - NSTimer 更改间隔性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24714375/

相关文章:

ios - 点击 map View 时未调用 didDeselectAnnotationView

iphone - UITableViewCell 的 textLabel.text 部分被省略号替换

javascript - 如何改善谷歌地图加载时间?

ios - 动态更改 Today Widget 的标题?

ios - UILabel不显示用户输入文本

objective-c - 如何将获取的对象保存到核心数据

objective-c - 在实际代码中使用 Uncle Bob 的 Clean Code 中的想法

c# - 在局部变量 C# 上声明字符串的局部常量有什么好处

c# - 多次使用属性时的性能考虑

android - 如何在 Android/iOS 设备上调试 unity3d?