Hello,
Recently in one of my projects, I faced a very strange issue. I have an http service call in app which was in background which brings some data. I want to show those data in Textviews in UI. Now the issue was it was not updating UI properly. I had five textviews and five strings in five variables. Out of which it was updating only one Textviews. Rest of the views were not updated. I was not sure what was the issue here as I was updating UI on main thread but still it was not working. See the below code.
Recently in one of my projects, I faced a very strange issue. I have an http service call in app which was in background which brings some data. I want to show those data in Textviews in UI. Now the issue was it was not updating UI properly. I had five textviews and five strings in five variables. Out of which it was updating only one Textviews. Rest of the views were not updated. I was not sure what was the issue here as I was updating UI on main thread but still it was not working. See the below code.
NSString *value1 = [jsonArray objectForKey:@"key1"];
NSString *value2 = [jsonArray objectForKey:@"key2"];
NSString *value3 = [jsonArray objectForKey:@"key3"];
NSString *value4 = [jsonArray objectForKey:@"key4"];
NSString *value5 = [jsonArray objectForKey:@"key5"];
As you see in above code I set five variables from my array which were created from JSON response of web service. Now I used dispatch_async to go on Main thread and set values to Text views.
dispatch_async(dispatch_get_main_queue(), ^{
[txt1 setText:value1];
[txt2 setText:value2];
[txt3 setText:value3];
[txt4 setText:value4];
[txt5 setText:value5];
});
As I mentioned an issue above that, it was setting value of only first text views. Others were blank. So I was not sure what was the issue. Later I realized that it was nil problem. Since I used local variables to store data, by the time my code inside dispatch_async runs, the scope of those variables were destroyed and there was a nil value. So other text views were blank.
So the solution was to keep variable initialization inside dispatch_async method. See the below code.
dispatch_async(dispatch_get_main_queue(), ^{
NSString *value1 = [jsonArray objectForKey:@"key1"];
NSString *value2 = [jsonArray objectForKey:@"key2"];
NSString *value3 = [jsonArray objectForKey:@"key3"];
NSString *value4 = [jsonArray objectForKey:@"key4"];
NSString *value5 = [jsonArray objectForKey:@"key5"];
[txt1 setText:value1];
[txt2 setText:value2];
[txt3 setText:value3];
[txt4 setText:value4];
[txt5 setText:value5];
});
That's it, it worked. After having initialization inside dispatch_async method, all the text views values were displayed properly. Hope this will help you and save you time.
No comments:
Post a Comment