Objective C- Trouble updating UI on main thread

后端 未结 2 684
野的像风
野的像风 2020-12-09 13:45

I am having some trouble updating my UI using performSelectorOnMainThread. Here is my situation. In my viewDidLoad I set up an activity indicator and a label. Then I call a

相关标签:
2条回答
  • 2020-12-09 14:05
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
     //load your data here.
     dispatch_async(dispatch_get_main_queue(), ^{
                    //update UI in main thread.
                });
    });
    
    0 讨论(0)
  • First of all you should not be using detachNewThreadSelector. You should use GCD and submit your background task to an async queue. Threads are costly to create. GCD does a much better job of managing system resources.

    Ignoring that, your code doesn't make a lot of sense to me. You submit a method, getSchoolList, to run on a background thread. You don't show the code that you are running in the background.

    Then use performSelector:withObject:afterDelay to run the method updateUI on the main thread after a fixed delay of 20 seconds.

    updateUI checks for self.schools, which presumably was set up by your background thread, and may or may not be done. If self.schools IS nil, you call fillPickerView using performSelectorOnMainThread. That doesn't make sense because if self.schools is nil, there is no data to fill the picker.

    If self.schools is not nil, you display an error, again using performSelectorOnMainThread.

    It seems to me that the logic on your check of self.schools is backwards. If it is nil you should display an error and if it is NOT nil you should fill the picker.

    Next problem: In both cases you're calling performSelectorOnMainThread:withObject:waitUntilDone: from the main thread. Calling that method from the main thread doesn't make sense.

    Third problem: It doesn't make sense to wait an arbitrary amount of time for a background task to run to completion, and then either succeed or fail. You won't have any idea what's going on for the full 20 seconds. If the background task finishes sooner, you'll never know.

    Instead, you should have your background task notify the main thread once the task is done. That would be a valid use of performSelectorOnMainThread:withObject:waitUntilDone:, while calling it from the main thread is not. (Again, though, you should refactor this code to use GCD, not using threads directly.

    It seems pretty clear that you are in over your head. The code you posted needs to be rewritten completely.

    0 讨论(0)
提交回复
热议问题