Reputation: 874
So I have a UITableCell that contains a button to add a specific friend on my app. When the friend request submits to the database on my app, I want the button text to change from "Add" to "Added". However, with my current code, the title does not change until I click the button the second time, even though it reaches the same part of the code, the button will not change unless I click it a second time (And I want to eventually disable this button once it changes the text).
Here is my code:
[[dynamoDBMapper save:friend] continueWithBlock:^id(AWSTask *task) {
if (task.error) {
NSLog(@"The request failed. Error: [%@]", task.error);
}
if (task.exception) {
NSLog(@"The request failed. Exception: [%@]", task.exception);
}
if (task.result) {
NSLog(@"Task result is %@", task.result);
NSLog(@"You've made it to the change text section");
[_addBtn setTitle:@"Added" forState:UIControlStateNormal];
}
return nil;
}];
Does anybody see what I am doing wrong? Or is there another way that I can change the button text for _addBtn
?
Upvotes: 0
Views: 135
Reputation: 3172
If you are not sure if that block is executed in main thread then you can check it by using this method: [NSThread isMainThread]
. That way, you will know the flow of your program. If it is not in the main thread, then you cannot update ANY UI element. All changes regarding UI MUST be done in the main thread. I just changed your code to give you a sample.
[[dynamoDBMapper save:friend] continueWithBlock:^id(AWSTask *task)
{
if (task.error)
{
NSLog(@"The request failed. Error: [%@]", task.error);
}
if (task.exception)
{
NSLog(@"The request failed. Exception: [%@]", task.exception);
}
if (task.result)
{
NSLog(@"Task result is %@", task.result);
NSLog(@"You've made it to the change text section");
//check if current block is in main thread.
if([NSThread isMainThread])
{
NSLog(@"The block is in main thread");
[_addBtn setTitle:@"Added" forState:UIControlStateNormal];
}
else
{
NSLog(@"The block is not in main thread");
dispatch_async(dispatch_get_main_queue(), ^
{
[_addBtn setTitle:@"Added" forState:UIControlStateNormal];
});
}
}
return nil;
}];
Upvotes: 0
Reputation: 1260
This is most likely an asynchronous issue. Create a method like
- (void)updateButton
{
dispatch_async(dispatch_get_main_queue(), ^{
// update button title
// disable button
});
}
And call this method from inside if (task.result) { }
Upvotes: 1