I want to provide read/write access to class property in side a timer’s event handler but also update the same property elsewhere in the class outside the event handler. What precautions do I need to take to make sure that the correct data is being read & updated?
Here’s the general logic:
// declared in the class header and initialized to 1 in init
@property (nonatomic, strong) NSNumber *sharedItem;
@property (nonatomic, assign) dispatch_source_t timer;
// Method invoked independent of the timer
- (void)doSomeWork {
// QUESTION: During a timer tick, will it access the correct version of
// sharedItem that is updated here?
// Do I need to protect this area with a critical section/lock?
sharedItem = [NSNumber numberWithInteger:[sharedItem intValue] + 1];
}
- (void)myTimerRelatedMethod {
// Creating the timer
_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(self.timer, startTime, interval, leeway);
// Timer's event handler run for each tick
dispatch_source_set_event_handler(self.timer, ^{
if ([sharedItem intValue] > 10) {
// 1. Do something
// 2. Then cancel the timer
}
});
dispatch_resume(self.timer);
}
For simple primitives you can just set the property to atomic, and you dont have to worry about read write inconsistencies between threads.
For pointers you should use @synchronize to avoid read write consistencies in addition to setting the property to atomic.
Also note that if your timer is in the same thread as the rest of your code (on the main thread+runloop), you dont need to do anything, as the timer event will be fired by the same runloop firing in the rest of the main thread code, and will not be truly concurrent.