简体   繁体   中英

cannot access self in objective-c codeblock

I am trying to call a function from a callback code block in objective-c, with the following code:

- (void)viewDidLoad
{
    [super viewDidLoad];

    WHVUser *user = [WHVUser sharedManager];
    WHVHTTPClient *http = [[WHVHTTPClient alloc] init];

    self.buttonInitRegistration.hidden = false; //this works!

    [http doRequestWithData:@{ @"access_token": user.token } atUrl:@"/me" andCallback:^(NSDictionary *data){
        NSLog(@"this block of code is certainly executed");
        self.buttonInitRegistration.hidden = false; //this doesn't!
    }];
}

Now, the problem is that basically when I do self.buttonInitRegistration.hidden = false inside the callback nothing happens but, if I do it outside, it does! I am pretty sure it has something to do with scoping, but I am not confident on how to fix this.

Any ideas? Thanks in advance.

you should do UI updates on the main thread, so assuming your callback is executed, try this;

  [http doRequestWithData:@{ @"access_token": user.token } atUrl:@"/me" andCallback:^(NSDictionary *data){
    NSLog(@"this block of code is certainly executed");
    dispatch_async(dispatch_get_main_queue(), ^{
      self.buttonInitRegistration.hidden = false; //this doesn't!
    });
}];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM