Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convenience initializer must delegate with self.init error for custom UIView initializer

I'm trying to create a custom init method for a UIView like so:

convenience init(frame: CGRect, tutorProfileImageURL: String?) {
    self.tutorProfileImageURL = tutorProfileImageURL
    super.init(frame: frame)
}

override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setup()
}

func setup() {
    _ = Bundle.main.loadNibNamed("TutorArrivedAlertView", owner: self, options: nil)?[0] as! UIView
    self.addSubview(customView)
    customView.frame = self.bounds
    tutorImageView.layer.cornerRadius = tutorImageView.frame.size.height/2
    tutorImageView.clipsToBounds = true
}

However I am getting the error:

Convenience initializer must delegate with self.init rather than chaining to a superclass initializer with super.init

like image 630
KexAri Avatar asked Mar 02 '17 06:03

KexAri


2 Answers

This error indicates, we shouldn't chain convenience initializer with its super class initializer.

We need to call following method

super.init(frame: frame)

inside this method

override init(frame: CGRect)

This is what it looks like:

convenience init(frame: CGRect, tutorProfileImageURL: String?) {
    self.init(frame: frame)
    self.tutorProfileImageURL = tutorProfileImageURL
}

override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
}

Check difference between Convenience and Designation initializers

like image 83
Sukhpreet Avatar answered Nov 13 '22 04:11

Sukhpreet


The convenience initializer uses his init for it. So just change the last line, to self.init

convenience init(frame: CGRect, tutorProfileImageURL: String?) {
    self.init(frame: frame)
    self.tutorProfileImageURL = tutorProfileImageURL
}
like image 41
José Neto Avatar answered Nov 13 '22 04:11

José Neto