I’ve tried the following:
- (void)setupTimer {
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(doSomething) userInfo:nil repeats:YES];
objc_setAssociatedObject(self, &key, timer, OBJC_ASSOCIATION_RETAIN);
[timer invalidate];
}
- (void)doSomething { /* ... */ }
- (void)afterDoingSomething { [objc_getAssociatedObject(self, &key) invalidate]; }
Yet, the timer doesn’t tick (I didn’t expected it to do so; this code just didn’t look much right to me) for some reason. Is there a way to make it… work?
You’re invalidating the timer immediately after creating and scheduling it. Remove the
[timer invalidate];line in-setupTimer:From the documentation:
Am I correct in assuming that this code is in a category? Otherwise, I can’t think of a good reason to make the timer an associated object instead of just using a regular instance variable for it.