You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xcode中点击播放按钮报错:-[UIViewController play:]无法识别选择器

问题分析与解决方案

错误提示-[UIViewController play:]: unrecognized selector sent to instance的核心原因是:触发按钮点击的视图控制器实例是系统默认的UIViewController,而非你自定义的WellnessViewController,导致系统找不到对应的play:方法。

解决步骤

  • 确认视图控制器类绑定正确

    1. 打开对应页面的Storyboard/XIB文件,选中视图控制器对象
    2. 打开右侧「Identity Inspector」(第三个标签页)
    3. 检查「Class」字段是否设置为WellnessViewController,同时确保「Module」字段为你的项目名称(避免类找不到)
    4. 如果之前是UIViewController,修改后记得点击回车确认
  • 重新绑定IBAction连接

    1. 右键点击播放/停止按钮,打开「Connections Inspector」
    2. 查看「Touch Up Inside」事件的连接对象,确认是WellnessViewController实例(通常对应「File's Owner」)
    3. 如果连接的是错误对象,点击连接后的「×」删除,然后重新拖拽按钮到WellnessViewController代码中,重新创建play和stop的IBAction
  • 清理缓存并重建项目
    执行Command+Shift+K清理项目缓存,再按Command+B重新编译运行,避免Xcode缓存导致的类加载异常

代码优化建议

  1. 避免强制解包music,用可选绑定防止文件不存在时崩溃:
override func viewDidLoad() {
    super.viewDidLoad()
    if let musicPath = Bundle.main.path(forResource: "Music", ofType: "mp3"),
       let musicURL = URL(fileURLWithPath: musicPath) {
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: musicURL)
            try AVAudioSession.sharedInstance().setCategory(.ambient)
            try AVAudioSession.sharedInstance().setActive(true)
        } catch {
            print("音频初始化失败:\(error)")
        }
    } else {
        print("未找到指定音频文件")
    }
}
  1. didReceiveMemoryWarning在iOS 10及以上已被废弃,可以直接删除该方法

内容的提问来源于stack exchange,提问作者Rebecca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 17:28:17