Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why do I get a Thread 1: EXC_BAD_ACCESS (code = EXC_I386_GPFLT)

var soundPoolLabel: UILabel {
  let label = UILabel(frame: CGRect(x: 20, y: 90, width: 540, height: 94))
  label.text = "SoundPool"
  label.textColor = UIColor.black
  label.font = UIFont(name: "Bodoni 72 Oldstyle", size: 80)
  let attributedString = NSMutableAttributedString(string: label.text!)
  attributedString.addAttribute(kCTKernAttributeName as NSAttributedStringKey, value: CGFloat(1.0), range: NSRange(location: 0, length: attributedString.length))
  label.attributedText = attributedString
  return label
}

soundPoolLabel.translatesAutoresizingMaskIntoConstraints = false
let topConstraint = soundPoolLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 90)
NSLayoutConstraint.activate([topConstraint])
like image 919
Gilchrist Avatar asked Jul 24 '18 00:07

Gilchrist


1 Answers

The label should not be a computed property. It should be initialized only once. Do something like this to fix the problem.

var soundPoolLabel: UILabel = {
  let label = UILabel(frame: CGRect(x: 20, y: 90, width: 540, height: 94))
  label.text = "SoundPool"
  label.textColor = UIColor.black
  label.font = UIFont(name: "Bodoni 72 Oldstyle", size: 80)
  let attributedString = NSMutableAttributedString(string: label.text!)
  attributedString.addAttribute(kCTKernAttributeName as NSAttributedStringKey, value: CGFloat(1.0), range: NSRange(location: 0, length: attributedString.length))
  label.attributedText = attributedString
  return label
}()

The reason for this is because every time you use soundPoolLabel, it will create a new instance of it instead of using the same one. The system can't find the new instance in the subview hierarchy, throwing EXC_BAD_ACCESS error

like image 149
Manoj Gubba Avatar answered Nov 15 '22 10:11

Manoj Gubba