首页 > 解决方案 > 为什么我得到一个线程 1:EXC_BAD_ACCESS(代码 = 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])

标签: swiftexc-bad-access

解决方案


标签不应是计算属性。它应该只初始化一次。做这样的事情来解决问题。

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,它都会创建它的一个新实例,而不是使用同一个实例。系统在子视图层次结构中找不到新实例,抛出 EXC_BAD_ACCESS 错误


推荐阅读