I have this optimization problem. I have a view in nib that consists of the picture and a label. Here is the way I load it from the nib:
@IBOutlet weak var imageView: UIImageView!
var view: UIView!
let nibName = "customView"
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
view = loadFromNib()
view.frame = self.bounds
imageView.image = CustomView.defaultImage
addSubview(view)
setupProfileView()
}
func loadFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: nibName, bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
It takes quite considerable amount of time whenever it loads. My UI is pretty heave on those customViews, I need to be able create around 50 of them and place them around without blocking the mainThread. It takes 170ms to create them using init with frame and 350 more to place them as subviews in my vc. Any suggestions how I can ease the load on the main thread in this case ? Maybe a programmatic approach would be better then the nib one ?
Just do the actual load in background thread, and once it is done - pass the reference back to the main thread, while showing a spinning wheel or something (if you want and if it is needed):
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
// Load your NIB here.
dispatch_async(dispatch_get_main_queue(), ^{
// Pass reference to main queue here.
});
});
This way you will do the heavy lifting in the parallel thread, while keeping the main thread free.