I was wondering whether there is a solution to raise an event once after 30 seconds or every 30 seconds in CocoaTouch ObjectiveC.
Asked
Active
Viewed 2.5k times
4 Answers
49
The performSelector: family has its limitations. Here is the closest setTimeout equivalent:
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 0.5);
dispatch_after(delay, dispatch_get_main_queue(), ^(void){
// do work in the UI thread here
});
EDIT: A couple of projects that provide syntactic sugar and the ability to cancel execution (clearTimeout):

Blago
- 4,697
- 2
- 34
- 29
-
can you reset the delay/timer if something happens before the delay time expires and have it start over? – topwik Sep 13 '13 at 19:54
-
1Can you dive in further on the limitations with `performSelector` ? – Jacksonkr Aug 18 '17 at 14:24
-
1@Jacksonkr The number of arguments that can be passed. – Blago Aug 18 '17 at 17:54
33
There are a number of options.
The quickest to use is in NSObject
:
- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay
(There are a few others with slight variations.)
If you want more control or to be able to say send this message every thirty seconds you probably need NSTimer
.

Stephen Darlington
- 51,577
- 12
- 107
- 152
-
1My guess is probably not (GCD is C-level and doesn't "know" about selectors; also this API predates GCD) but it's possible that it does use it under the hood. – Stephen Darlington Aug 18 '17 at 18:13
14
Take a look at the NSTimer
class:
NSTimer *timer;
...
timer = [[NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(thisMethodGetsFiredOnceEveryThirtySeconds:) userInfo:nil repeats:YES] retain];
[timer fire];
Somewhere else you have the actual method that handles the event:
- (void) thisMethodGetsFiredOnceEveryThirtySeconds:(id)sender {
NSLog(@"fired!");
}

Alex Reynolds
- 95,983
- 54
- 240
- 345
3
+[NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:]
You may also want to look at the other NSTimer
methods