如果你有一个计时器的cancel_handler,你可以直接引用和重置任何声明为具有'assign'属性的属性的ivars,或者你必须先将它指定为__block吗?
@interface SomeClass: NSObject { }
@property (nonatomic, assign) dispatch_source_t timer;
@end
// Class implementation
@implementation SomeClass
@synthesize timer = _timer;
- (void)startTimer
{
dispatch_queue_t globalQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,
0, 0, globalQ);
dispatch_time_t startWhen = dispatch_walltime(DISPATCH_TIME_NOW, NSEC_PER_SEC * 1);
dispatch_source_set_timer(_timer, startWhen, 1 * NSEC_PER_SEC, 5000ull);
dispatch_source_set_event_handler(_timer, ^{
// timer's event handler
});
// VERSION 1:
// Is it okay to reference and assign self.timer to nil
// or does it have to be declared as __block as in VERSION 2?
dispatch_source_set_cancel_handler(_timer, ^{
dispatch_release(_timer);
self.timer = nil;
});
// VERSION 2:
__block myTimer = self.timer;
dispatch_source_set_cancel_handler(_timer, ^{
dispatch_release(myTimer);
myTimer = nil;
});
dispatch_resume(_timer);
}
答案 0 :(得分:0)
你可以参考ivars就好了。但是,这些引用带有对self
的隐式引用,因此您需要警惕保留周期。例如,如果您直接引用ivar,请不要期望在-dealloc
中关闭计时器,因为永远不会调用它。