Swift开发遇到"Thread 1: breakpoint 1.1 (1)"错误无法解决
触发lldb断点的原因及修复方案
问题根源
- 大概率是Xcode开启了未注意到的全局断点:包括Thread断点或Swift异常断点,这类断点会在程序出现运行时异常时自动暂停,无明确报错直接显示(lldb)提示。
- 代码中存在强制解包的崩溃风险:两处
!强制解包操作sender.currentTitle!、eggTimes[sender.currentTitle!]!,如果按钮标题不在eggTimes的预设键范围内,会直接触发运行时崩溃,引发调试器暂停。 - 隐含的定时器逻辑问题:你注释了
timer.invalidate(),每次点击按钮都会创建新的重复定时器,旧定时器不会停止,会导致计时逻辑异常,也可能触发运行时异常。
修复步骤
- 先排查Xcode断点:按快捷键
⌘7打开断点导航栏,删除所有不需要的蓝色激活状态的全局断点,再重新运行测试。 - 优化代码逻辑,替换强制解包为安全可选绑定,恢复定时器销毁逻辑,计时结束后主动停止定时器,修复后代码如下:
import UIKit class ViewController: UIViewController { let eggTimes = ["Soft":3, "Medium":5, "Hard":7] var totalTime = 0 var progress: Float = 0.0 var passedTime = 0 var timer: Timer? // 改成可选类型,避免初始化无效定时器 @IBAction func hardnessSelected(_ sender: UIButton) { // 先销毁旧定时器,避免多个定时器同时运行 timer?.invalidate() // 安全取值,避免强制解包崩溃 guard let title = sender.currentTitle, let time = eggTimes[title] else { return } totalTime = time timer = Timer.scheduledTimer(timeInterval: 1.0, target: self,selector: #selector(updateTimer), userInfo: nil, repeats: true) } @objc func updateTimer() { if totalTime > 0 { print(totalTime) totalTime -= 1 } else { // 计时结束后主动销毁定时器 timer?.invalidate() timer = nil } } }
内容的提问来源于stack exchange,提问作者Kavya Khurana
相关产品推荐
相关产品推荐

