swift - 为什么我得到一个线程 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])
解决方案
标签不应是计算属性。它应该只初始化一次。做这样的事情来解决问题。
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 错误
推荐阅读
- python - TypeErr:无法腌制“_thread.RLock”对象 - 目标:以 .joblib 格式保存模型以便在需要 .joblib 后重用
- javascript - DiscordJS 验证命令
- sql - 查询 - 计算具有相同列的 2 个 DB 表之间的差异
- angular - 如何使用 IdentityServer4 身份验证以静默方式重新登录用户
- python-3.x - 如何根据模式屏蔽和替换字符串中的字符?
- image - Visual Studio 中的 DarkImages 文件夹是做什么用的?
- python - 如何在熊猫中使用嵌套字典映射变量?
- c# - ArgumentOutOfRangeException:从字符串中提取字符串
- performance - 我试图通过删除分配来缩短代码,但结果以某种方式完全改变了。有什么解释吗?
- javascript - s3 预签名的 url Javascript 代码不返回完整的 url