Search code examples
iosnsarraynstimernstimeinterval

Triggering a method at times stored in Array using NSTimer


I have an Array that have stored times. I want NStimer to trigger at times stored in that array. For example, in array a[] i have 2, 5 and 10 seconds and want NSTimer to trigger a method at these times. I do have another NSTimer that keep updating the time instance variable every second.


Solution

  • A simple solution would be to loop through your array and schedule method calls with GCD

    for (NSNumber *time in array) {
        NSTimeInterval delay = [time doubleValue];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                <#code to be executed after a specified delay#>
            });
    }