2016-08-17 24 views
1

我想在不同的時間間隔翻頁10頁。我需要創建10個定時器來翻轉?或者我可以創建一個數組間隔並將它們插入到計時器中?我是以更簡單的方式做到這一點?Objective-C:通過不同的時間間隔翻頁

+0

您只需要一個定時器以任何頁面使用的最小時間間隔。然後在每個計時器事件上,檢查哪些頁面間隔已過期。 –

+0

@johnelemans你能給我代碼示例嗎? –

回答

0

有很多方法可以做到這一點。這裏有一個:

這可能是一個很好的解決方案,如果你的間隔時間不規則和相距甚遠。如果它們間隔更均勻(例如,第一秒是兩秒,接下來是四秒),那麼你可以簡化這個設計。但是,我假設你只是想能夠傳遞一系列時間間隔,然後讓代碼完成所有的處理。

  1. 對於這個實現,我們將需要一個實例變量來存放一個定時器數組。如果您更喜歡實例變量,請使用屬性。
 

    @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 ]];

    那將回叫multipleTimersFlip方法每隔5,7.5,和10秒。

    記住調用multipleTimersStopAll可以在不需要它時停止所有這些操作。