【问题标题】:Using multiple NSTimers on iOS - Only one timer fires在 iOS 上使用多个 NSTimer - 只有一个计时器触发
【发布时间】:2011-04-01 20:46:45
【问题描述】:

遇到问题需要帮助。

目标
我正在整理一个 iOS 图书应用程序,它使用 NSTimers 在加载视图后触发几个交错的动画事件。我创建了一个 MethodCallerWithTimer 类来帮助我做到这一点(代码在底部)。

到目前为止我的解决方案
当我使用 MethodCallerWithTimer 类时,我将 objectOwningMethod 分配为我的 UIViewController 子类对象(它是一个书页),然后将该方法作为该类中的实例方法。这是我指定的一个方法示例 - 非常简单地打开屏幕上的一些艺术作品:

- (void) playEmory {
   [emoryRedArt setHidden:NO];
}

我的问题
当我创建多个 MethodCallerWithTimer 实例然后加载视图并启动它们时,我只会让 FIRST 事件发生。其他计时器都没有调用它们的目标方法。我怀疑我不明白我要求 NSRunLoop 做什么或类似的事情。

有什么想法吗?

这是我的 MethodCallerWithTimer 类:

@interface MethodCallerWithTimer : NSObject {
    NSTimer * timer;
    NSInvocation * methodInvocationObject;
    NSNumber * timeLengthInMS;
}

- (id) initWithObject: (id) objectOwningMethod AndMethodToCall: (SEL) method;
- (void) setTime: (int) milliseconds;
- (void) startTimer;
- (void) cancelTimer;

@end

及实施:

#import "MethodCallerWithTimer.h"

@implementation MethodCallerWithTimer

- (id) initWithObject: (id) objectOwningMethod AndMethodToCall: (SEL) method {
    NSMethodSignature * methSig = [[objectOwningMethod class] instanceMethodSignatureForSelector:method];
    methodInvocationObject = [NSInvocation invocationWithMethodSignature:methSig];
    [methodInvocationObject setTarget:objectOwningMethod];
    [methodInvocationObject setSelector:method];
    [methSig release];
    return [super init];
}
- (void) setTime: (int) milliseconds {
    timeLengthInMS = [[NSNumber alloc] initWithInt:milliseconds];
}
- (void) startTimer {
    timer = [NSTimer scheduledTimerWithTimeInterval:([timeLengthInMS longValue]*0.001) invocation:methodInvocationObject repeats:NO];
}
- (void) cancelTimer {
    [timer invalidate];
}
-(void) dealloc {
    [timer release];
    [methodInvocationObject release];
    [timeLengthInMS release];
    [super dealloc];
}

@end

【问题讨论】:

    标签: objective-c ios concurrency nstimer nsrunloop


    【解决方案1】:

    这些看起来像是延迟后的一次性发射;你有没有考虑过使用类似的东西:

    [myObject performSelector:@selector(playEmory) withObject:nil afterDelay:myDelay];
    

    其中myObject 是具有playEmory 例程的实例,myDelay 是您希望操作系统在拨打电话前等待的float 秒数?

    你可以找到更多关于performSelectorhere的信息。

    【讨论】:

    • 伟大的建议,fbrereto。谢谢。这对我有用。我仍然有点好奇为什么我以前的实现没有,但我应该能够很好地解决这个问题。
    猜你喜欢
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-15
    • 2015-08-08
    • 2017-08-21
    • 1970-01-01
    相关资源
    最近更新 更多