I've made a Macro that will do this and auto handle dealloc, arc, retain cycles etc. No need to worry about using weak references. It will also always be on main thread
#define inlineTimer(__interval, __block) {\
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((0.0) * NSEC_PER_SEC)), dispatch_get_main_queue(), (__block));\
[NSTimer scheduledTimerWithTimeInterval:__interval repeats:YES block:^(NSTimer *__timer) {\
if (self.window != nil) {\
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((0.0) * NSEC_PER_SEC)), dispatch_get_main_queue(), (__block));\
} else {\
[__timer invalidate];\
}\
}];\
}
Example usage:
__block ticks = 0;
inlineTimer(0.5, ^{
ticks++;
self.label.text = [NSString stringWithFormat:@"Ticks: %i", ticks];//strong reference to self and self.label won't cause retain cycle! Wahoo
});
Note that self.label is not a weak reference, yet this will all be automatically released due to how the macro is structured.
Naturally this only works w/ UI classes, given that it's checking .window for when it should dealloc.