I’m trying to set the alpha of a label, inside a block statement and therefore I’m calling self. As I understand it, I can’t call self directly from within a block statement, so I have to make a reference of self first.
This is the code I have, but it’s not working:
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];
}
}];
Any ideas of what might be the problem?
UPDATE 1
I ‘ve also tried to only reference self, but with no luck:
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];
}
}];
UPDATE 2
Just checked if error label is nil and it doesn’t seem to be:
if (self.errorLabel != nil) {
NSLog(@"Errorlabel is not nil"); //Errorlabel is not nil
}
CAUSE OF ERROR
The error was that I had this code right after I wanted to fade out the label:
[UIView animateWithDuration:0.2f animations:^{
//self.errorLabel.alpha = 0.0f;
} completion:^(BOOL success){
}];
I don’t fully understand why this should cause trouble?
You need to ensure all your UI calls are made from the main thread. This includes any
animateWith...calls. The quickest way is to simply wrap them in a dispatch block, like so:If you are unsure if your code is running on the main thread you can debug with the following statement.
Always lookout for completion handlers on asynchronous network APIs. Make sure their documentation says the completion handler will be called on the main thread. If it doesn’t, play it safe and transfer any UI related work to the main thread.