Reputation: 488
When do outlets get bound to a UITableViewCell instance? If I print myLabel in the debugger, it's nil and prints:
fatal error: unexpectedly found nil while unwrapping an Optional value
class MyTableViewCell: UITableViewCell {
@IBOutlet var myLabel: UILabel!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
print("\(myLabel)")
}
}
Upvotes: 1
Views: 1058
Reputation: 7736
If you are connecting an outlet from the Main Storyboard, your problem could arise if the outlet was accidentally deleted. Recreate the outlet and the label will not be nil anymore.
Upvotes: 0
Reputation: 96
Outlets are not yet set when the init method of your tableview cell is called!
I'm not sure what your intention is:
If you want to make sure you are not unwrapping a nil optional value just use if let
like this:
if let label = myLabel {
print("\(label)")
}
If you want to setup the cell of your tableView, you should first register the cell by calling tableView.registerNib(UINib(nibName: "MyTableViewCell", bundle: nil), forCellReuseIdentifier: "reuse")
. Then dequeue the cell in cellForRowAtIndexPath
using tableView.dequeueReusableCellWithIdentifier("reuse")
and make sure you set the values of your cell in awakeFromNib
:
override func awakeFromNib() {
super.awakeFromNib()
//you can be sure that myLabel is initialzed here
print("\(myLabel)")
}
Upvotes: 3
Reputation: 294
The issue is that you are running into a case where myLabel is nil. It could be while the table view cell is being recycled.
Upvotes: -1