起初在学习使用swift时,对闭包的变量捕获部分并没有认真的去了解,想当然的认为应给和OC中的block捕获规则一样,结果最近在使用中产生了错误,回过头来再去了解时,发现了二者的捕获规则有着很大的差异,这里只说现象,提醒大家在使用中多加注意,至于原因,有兴趣的可以分别去具体了解一下闭包与block的变量捕获机制.
先看OC代码
TestModel *test = [[TestModel alloc] init];
test.name = @"1";
dispatch_after(2, dispatch_get_global_queue(0, 0), ^{
NSLog(@"%@",test.name);
});
test.name = @"2";
结果:2
TestModel *test = [[TestModel alloc] init];
test.name = @"1";
dispatch_after(2, dispatch_get_global_queue(0, 0), ^{
NSLog(@"%@",test.name);
});
test = [[TestModel alloc] init];
test.name = @"2";
结果:1
熟悉OC的同学应该可以理解上面两个例子的结果输出
再看看swift