0

so here is the problem:

I've got a few heavy views with many subviews, which I need to load and then to display. I want to do it asynchronously so that I don't block my main thread. When I tried to do it asynchronously I encountered the following dilemma:

After all of the heavy lifting job has been done and I return to the main queue to actually display that stuff, I get problems. First of all even though everything is done it takes 30-60 seconds for all the views to become visible. Sometimes they get misplaced. What could I be doing wrong and what should I be looking for ?

private func loadScrollViews() {
    let qos = Int(QOS_CLASS_USER_INTERACTIVE.value)
    dispatch_async(dispatch_get_global_queue(qos, 0)) { () -> Void in
        // Creating many UIViews
        for var i = 0; i < 100; i++ {
            let view = UIView(frame: someFrame)
            self.viewCollection.append(view)
        }
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            self.displayViews()
        })
    }
}

private func displayViews() {
    for view in self.viewCollection {
        self.contentView.addSubview(view)
    }
    self.activityIndicator.stopAnimating()
    self.contentView.hidden = false
}

After displayViews gets executed as I said views take almost a minute to appear on the screen.

3
  • 1
    Update your question with relevant code. We can't help you fix what we can't see. Commented Aug 13, 2015 at 17:38
  • Create views on main thread Commented Aug 13, 2015 at 17:50
  • Ok, I will not argue that it is not right, but why is so? Any technical insight? Commented Aug 13, 2015 at 17:51

1 Answer 1

3

UIView manipulation should be done on main thread from doc

Threading Considerations

Manipulations to your application’s user interface must occur on the main thread. Thus, you should always call the methods of the UIView class from code running in the main thread of your application. The only time this may not be strictly necessary is when creating the view object itself but all other manipulations should occur on the main thread.

if you have to create many UIView object then do it like this dispatch_async() but use main_queue for this purpose. And one more thing if you want use background thread then think about using CALayer we can do most of CALayer work on background thread

Sign up to request clarification or add additional context in comments.

2 Comments

More than recommended. UIKit objects are not thread-safe. Creating UIView objects on a background thread is not supported. Don't do that.
Agreed I should change recommended word

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.