0

I'm trying to create a method with an argument in objective-c, the argument is an amount of seconds before the actual method starts.

I'm trying to avoid using the [self performSelector:(SEL) withObject:(id) afterDelay:(NSTimeInterval)]; because having the delay within my method would actually save me a lot of coding as I am planning to add other arguments to this method.

Example of the method:

-(void) startMethodAfterArgumentDelay: (NSTimeInterval *)delay{
     NSLog(@"perform action after argument delay");
}

and how to call it:

[self startMethodAfterArgumentDelay:3.0f];

Any help would be greatly appreciated!

PhilBlais
  • 1,076
  • 4
  • 13
  • 36

3 Answers3

2

If you don't want to use any 3rd party libraries as the other answer suggested, this is easy enough to implement yourself using GCD's dispatch_after(). Just note that this method is a asynchronous, so your method will return immediately even though the contents of the block are delayed.

- (void)startMethodAfterArgumentDelay:(NSTimeInterval)delay
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"perform action after argument delay");
    });
}
Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
1

You can use BlocksKit and then write code like that:

[self bk_performBlock:^(id obj) {
    //code
} afterDelay:delay];
Azat
  • 6,745
  • 5
  • 31
  • 48
1

Just feed delay to dispatch_after.

dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
    // do whatever
});
matt
  • 515,959
  • 87
  • 875
  • 1,141