结论,对于局部变量,block中可以访问到,但是不能修改,如果要修改,就要在这个局部变量前面加上__block;
__block int time = 100;
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(self.timer, ^{
time -= 1;
NSLog(@"%d",time);
});
dispatch_resume(self.timer);
众所周知,__weak是防止block中循环应用,而__strong是防止block执行中weakSelf被释放了,这里__strong需要在block中持有,若在block外持有会导致循环引用,如果在block中,strongSelf调不起方法,说明在执行block前weak self已经被释放了。