在使用GCD定时器时,系统的代码块并不好用
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
dispatch_source_set_event_handler(timer, ^{
NSLog(@"+++++定时器+++++");
});
dispatch_resume(timer);
只有将 dispatch_source_t timer 写成属性handle event才会被调用
@property (nonatomic, strong) dispatch_source_t timer;
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
dispatch_source_set_event_handler(_timer, ^{
NSLog(@"+++++定时器+++++");
});
dispatch_resume(_timer);
这是为什么呢?
PHP中文网2017-04-18 09:26:44
Memory management... Because you are an ARC, the object you create will be valid within its scope. Once it goes out of its scope, if there is no strong reference, the object will be destroyed naturally. This is what you can only use if you write it as an attribute. reason.