0

I am trying to make a protocol in a UITableViewCell class but when i declare my delegate, I get an error in both required init?(coder aDecoder: NSCoder) and override init(style: UITableViewCellStyle, reuseIdentifier: String?)

Error : - Property 'self.delegate' not initialised at super.init

This is my subclass:-

import UIKit

protocol tableCellBtnActionDelegate{

func removeRowAtIndex(_: Int)

}

class FriendsListTableViewCell: UITableViewCell {
@IBOutlet weak var friendListAddBtn: UIButton!
var usersId : String!
var buttonText : String!
var indexPath : Int!
let delegate : tableCellBtnActionDelegate!
override func awakeFromNib() {
    super.awakeFromNib()
    friendListAddBtn.layer.cornerRadius = 4
    friendListAddBtn.layer.backgroundColor = UIColor(red: 121.0/255.0, green: 220.0/255.0, blue: 1, alpha: 1).CGColor
}

required init?(coder aDecoder: NSCoder) {

    super.init(coder: aDecoder)
}
override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {

    super.init(style: style, reuseIdentifier: reuseIdentifier)

}
}

Errors

Ashish Thakkar
  • 944
  • 8
  • 27
Dravidian
  • 9,945
  • 3
  • 34
  • 74

3 Answers3

2

Well you haven't initialize it, so the compiler gives you a warning. I would advise you to modify the delegate to be optional and set your delegate whenever you need it.

var delegate : tableCellBtnActionDelegate? 

You should also handle the case where delegate is not set(nil).

l.vasilev
  • 926
  • 2
  • 10
  • 23
  • I did this, didnt help. The delegate function doesnt gets called , when i changed it back to `var delegate : tableCellBtnActionDelegate!` it gave me an error : ' nil '. – Dravidian Jul 18 '16 at 13:31
  • 1
    This is the correct answer to fix the problem in your question. You need to make sure you are setting the delegate correctly and calling the delegate method. You haven't shown either of those bits of code – Paulw11 Jul 18 '16 at 13:44
1

Change

let delegate : tableCellBtnActionDelegate!

to

var delegate : tableCellBtnActionDelegate!

or you can't set value to delegate property ever

Yury
  • 6,044
  • 3
  • 19
  • 41
  • You *can* set a value to a `let` + implicitly unwrapped optional: in an init. OP just doesn't do it. – Eric Aya Jul 18 '16 at 12:51
  • @EricD ty for comment, it make answer more full; I just don't believe that he want to set delegate in init – Yury Jul 18 '16 at 12:56
1

You got a warning because you are not initialising the delegate property. It should actually be a weak property, or you will retain a reference to the delegate object, which you usually don't want to do. So the best approach would be:

weak var delegate : tableCellBtnActionDelegate?

And then you have to use it like this:

self.delegate?.notifyAboutSomething()

Community
  • 1
  • 1
gskbyte
  • 467
  • 3
  • 13