我想以不同的时间间隔转换10页。我需要为翻转创建10个计时器吗?或者我可以创建一个数组间隔并将它们插入计时器? Сan我以更简单的方式做到了吗?
答案 0 :(得分:0)
有很多方法可以做到这一点。这是一个:
如果您的间隔不规则且距离很远,这可能是一个很好的解决方案。如果它们间隔更均匀(例如,第一个是两秒,接下来是四秒),那么您可以简化此设计。但是,我假设您只想传递一系列间隔,然后让代码处理所有这些。
@implementation ViewController { NSArray *_multipleTimerInstances; }
- (void)multipleTimers:(NSArray *)durations { // Get rid of any timers that have already been created. [self mulitpleTimerStopAll]; NSMutableArray *newTimers = [NSMutableArray new]; // Create the new timers. [durations enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { // Each element of the durations array specifies the flip interval in seconds. double duration = [(NSNumber *)obj doubleValue]; // Schedule it. NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:duration target:self selector:@selector(multipleTimersFlip:) userInfo:[NSNumber numberWithInteger:idx] repeats:YES]; // Keep a reference to the new timer so we can invalidate it later, if we want. [newTimers addObject:timer]; }]; // We now have a new list of timers. _multipleTimerInstances = [newTimers copy]; } - (void)multipleTimersFlip:(NSTimer *)timer { NSInteger index = [timer.userInfo integerValue]; // The integer index corresponds to the index of the timer in the array passed // to the multipleTimers method. NSLog(@"Flip page for timer with index: %ld", (long)index); } - (void)mulitpleTimerStopAll { // Get rid of any timers that have already been created. for (NSTimer *timer in _multipleTimerInstances) [timer invalidate]; // And nil out the array, they're gone. _multipleTimerInstances = nil; }
[self multipleTimers:@[ @5.0, @10.0, @7.5 ]];
那将每隔5,7.5和10秒回调一次multipleTimersFlip方法。
请记住,当您不需要时,请调用multipleTimersStopAll来停止所有这些操作。