我想在计时器的事件处理程序中提供对类属性的读/写访问,但还要在事件处理程序之外的类的其他地方更新相同的属性。我需要采取哪些预防措施来确保读取和更新正确的数据?
这是一般逻辑:
// 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);
}