Created by Jamz Tang at 20 August 2011

Cancelable Scheduled Blocks in Objective-C

Sometimes you'd really want to perform a delayed action for your apps. We'll create a category on NSObject to provide a really handy usage.

The best thing with this snippet is your scheduled operations are cancelable, so you can choose to only perform your latest triggered operation (e.g. for your table view cells maybe?)

/*
 * This file is part of the http://ioscodesnippet.com
 * (c) Jamz Tang <jamz@jamztang.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#import <Foundation/Foundation.h>

@interface NSObject (JTCancelableScheduledBlock)

- (void)performBlock:(void (^)(void))block afterDelay:(NSTimeInterval)delay;
- (void)performBlock:(void (^)(void))block afterDelay:(NSTimeInterval)delay cancelPreviousRequest:(BOOL)cancel;

@end
/*
 * This file is part of the http://ioscodesnippet.com
 * (c) Jamz Tang <jamz@jamztang.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#import "NSObject-JTCancelableScheduledBlock.h"

@implementation NSObject (JTCancelableScheduledBlock)

- (void)delayedAddOperation:(NSOperation *)operation {
    [[NSOperationQueue currentQueue] addOperation:operation];
}

- (void)performBlock:(void (^)(void))block afterDelay:(NSTimeInterval)delay {
    [self performSelector:@selector(delayedAddOperation:)
               withObject:[NSBlockOperation blockOperationWithBlock:block]
               afterDelay:delay];
}

- (void)performBlock:(void (^)(void))block afterDelay:(NSTimeInterval)delay cancelPreviousRequest:(BOOL)cancel {
    if (cancel) {
        [NSObject cancelPreviousPerformRequestsWithTarget:self];
    }
    [self performBlock:block afterDelay:delay];
}

@end

Usage:

[self performBlock:^(void) {
     NSLog(@"delayed operation!");
} afterDelay:2];

Handy right?

You may also interest about how others doing in alternative ways.

Delayed Blocks in Objective-C

Easy Delayed Messaging using NSProxy and NSInvocation

Updated 17 May 2012: Thanks Jesse Armand ā€¸suggesting this great article for using the dispatch_source in GCD


Installation

Using CocoaPods: [?]
pod 'NSObject-JTCancelableScheduledBlock', '~> 0.0.1'

Clone this repository:
git clone git://gist.github.com/1571800.git NSObject-JTCancelableScheduledBlock

Download | More...


If you think this is useful, share this article with your friends :)

blog comments powered by Disqus

ioscodesnippet.com