Davit Siradeghyan
Davit Siradeghyan

Reputation: 6323

UIBarButtonItem image not set

I have very strange problem. I'm initializing some UI elements inside completion block of AFNetworking, and only one of them (UIBarButtonItem) is not initializing. Here is my code which is placed in viewDidLoad:

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

[m_httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

     NSError* error;
     self.m_pointData = [NSJSONSerialization
                        JSONObjectWithData:responseObject
                        options:kNilOptions
                        error:&error];

     [self InitializeFields];
 }
 failure:^(AFHTTPRequestOperation *operation, NSError *error)
 {
     NSLog(@"Error in get point response: %@", error);
 }];

[operation start];

}

I do initialization inside InitializeFields and here is the code:

self.m_placeName.text = [self.m_pointData objectForKey:@"name"];

self.m_placeLocation.text = [self.m_pointData objectForKey:@"city"];

NSArray* comments = [self.m_pointData objectForKey:@"comments"];

const int commentsCount = [comments count];

self.m_commentsCount.text = [NSString stringWithFormat:@"%d", commentsCount];

self.m_scrollView.m_address.text = [self.m_pointData objectForKey:@"address"];
self.m_scrollView.m_email.text = [self.m_pointData objectForKey:@"email"];
self.m_scrollView.m_phone.text = [self.m_pointData objectForKey:@"tel"];
self.m_scrollView.m_link.text = [self.m_pointData objectForKey:@"website"];

self.m_rightBtn.image = [UIImage imageNamed:@"favorite_star_inactive.png"];

Only the last line – self.m_rightBtn.image = [UIImage imageNamed:@"favorite_star_inactive.png"]; – does not work. When I'm moving it to viewDidLoad it works. Something with completion block, but I don't know what.

Upvotes: 1

Views: 115

Answers (2)

Michael Dautermann
Michael Dautermann

Reputation: 89559

UI things are supposed to happen on the main thread, not on secondary threads (which completion blocks may be).

Do the UI stuff within this:

dispatch_async(dispatch_get_main_queue(), ^{
    // This block will be executed asynchronously on the main thread.
});

and all will be well. There's more detail to be found in this related question & answer.

Upvotes: 1

Roma
Roma

Reputation: 1107

I can assume that this block is not in the main thread. Try to do to this in main thread:

dispatch_async(dispatch_get_main_queue(), ^{
        //update button
    });

Also next assumption is that image hasn't initialized while you're accessing it in block. Add check:

if (!self.m_rightBtn.Image) {
    self.m_rightBtn.Image = [UIImage new];
}

Upvotes: 2

Related Questions