Search code examples
iosswiftios9nsnotificationcenter

NSNotification with delay


How to post NSNotification with delay.

One solution that is in my mind :- post notification in performSelectorAfterDelay method. Is there any better solution for this.

Is NSNotificationQueue can help me to achieve this ?


Solution

  • Make use of GCD's dispatch_after() method. In Objective-C, this would look like:

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotification:someNotification];
    });
    

    Update: Swift 3

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(5)) { 
        NotificationCenter.default.post(someNotification)
    }