我有一个关于iOS中块的自我强弱参考的问题.我知道在块内引用self的正确方法是在块外创建一个弱引用,然后在块内强引用该弱引用,如下所示:
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^ {
typeof(self) strongSelf = weakSelf;
NSLog(@"%@", strongSelf.someProperty);
});
Run Code Online (Sandbox Code Playgroud)
但是,如果你有嵌套块会发生什么?一组参考文献足够吗?或者您是否需要为每个区块设置新组?例如,以下哪项是正确的?
这个:
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^ {
typeof(self) strongSelf = weakSelf;
NSLog(@"%@", strongSelf.someProperty);
dispatch_async(dispatch_get_main_queue(), ^ {
strongSelf.view.frame = CGRectZero;
});
});
Run Code Online (Sandbox Code Playgroud)
或这个:
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^ {
typeof(self) strongSelf = weakSelf;
NSLog(@"%@", strongSelf.someProperty);
__weak typeof(strongSelf) weakSelf1 = strongSelf;
dispatch_async(dispatch_get_main_queue(), ^ {
typeof(strongSelf) strongSelf1 = weakSelf1;
strongSelf1.view.frame = CGRectZero;
});
});
Run Code Online (Sandbox Code Playgroud)
非常感谢任何信息或解释!
我想了解这段代码:
__weak LoginViewController *weakSelf = self;
NSTimer *networkTimer = [NSTimer pym_scheduledTimerWithTimeInterval:15.0 block:^{
LoginViewController *strongSelf = weakSelf;
[strongSelf timeout];
} repeats:NO];
[PYMAuthManager loginWithUsername:username password:password completionHandler:^(BOOL successful) {
if (successful) {
[networkTimer invalidate].......
Run Code Online (Sandbox Code Playgroud)
这是一个网络计时器,如果没有活动,将在15秒后超时.为什么在块中创建指针*strongSelf = weakSelf?使用[weakSelf timeout]不行吗?我明白无论何时在块中访问self我们都必须使用弱引用,为什么在这里创建另一个指针?任何帮助都会很棒,谢谢.