我正在尝试在 block 语句内设置标签的 alpha,因此我调用 self.据我了解,我无法直接从 block 语句中调用 self,因此我必须首先引用 self。
这是我的代码,但它不起作用:
self.accountStore = [[ACAccountStore alloc] init];
__weak UILabel *weakSelf = self.errorLabel;
[self.accountStore requestAccessToAccountsWithType:twitterType options:NULL completion:^(BOOL granted, NSError *error) {
if (!granted) {
[weakSelf setAlpha:0.0f];
}
}];
对可能出现的问题有什么想法吗?
更新 1
我也尝试过只引用 self,但没有成功:
self.accountStore = [[ACAccountStore alloc] init];
__weak FrontPageViewController *weakSelf = self;
[self.accountStore requestAccessToAccountsWithType:twitterType options:NULL completion:^(BOOL granted, NSError *error) {
if (!granted) {
[weakSelf.errorLabel setAlpha:0.0f];
}
}];
更新 2
刚刚检查错误标签是否为零,但似乎不是:
if (self.errorLabel != nil) {
NSLog(@"Errorlabel is not nil"); //Errorlabel is not nil
}
错误原因
错误是我在想要淡出标签后立即得到了以下代码:
[UIView animateWithDuration:0.2f animations:^{
//self.errorLabel.alpha = 0.0f;
} completion:^(BOOL success){
}];
我不完全明白为什么这会引起麻烦?
最佳答案
您需要确保所有 UI 调用都是从主线程进行的。这包括任何 animateWith...
调用。最快的方法是简单地将它们包装在调度 block 中,如下所示:
dispatch_async(dispatch_get_main_queue(), ^{
[UIView animateWithDuration:0.2f
animations:^{
self.errorLabel.alpha = 0.0f;
}
completion:nil];
});
如果您不确定代码是否在主线程上运行,您可以使用以下语句进行调试。
NSLog(@"Is main thread = %@",(dispatch_get_main_queue() == dispatch_get_current_queue())?@"YES":@"NO");
始终留意异步网络 API 上的完成处理程序。确保他们的文档说明将在主线程上调用完成处理程序。如果没有,请谨慎行事,并将任何与 UI 相关的工作转移到主线程。
关于iphone - 保留的 self 在 block 语句内不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13435227/