1

需要帮助解决问题。

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

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

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

我的问题
当我创建多个MethodCallerWithTimer实例然后加载视图并启动它们时,我只会让第一个事件发生。其他计时器都没有调用它们的目标方法。我怀疑我不明白我要求 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
4

1 回答 1

4

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

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

例程myObject的实例在哪里,是您希望操作系统在拨打电话之前等待的秒数吗?playEmorymyDelayfloat

performSelector 您可以在此处找到有关此风味的更多信息。

于 2011-04-01T21:11:46.020 回答