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

将CoreML模型集成到手部姿态分类App时遇init()弃用报错如何解决

报错原因

苹果在新版本CoreML框架中废弃了模型自动生成类的无参初始化方法init(),要求使用带configuration参数的初始化方法显式处理可能的初始化错误。

正确实现方式

推荐使用懒加载的方式初始化模型,避免属性初始化阶段抛出无法捕获的错误:

private lazy var model: VNCoreMLModel? = {
    do {
        // 使用官方推荐的带configuration参数的方法初始化自定义模型
        let digitsModel = try Digits(configuration: .init())
        // 转换为Vision框架可用的CoreML模型
        let vnModel = try VNCoreMLModel(for: digitsModel.model)
        return vnModel
    } catch {
        // 自定义错误处理逻辑,可根据业务需要添加降级方案
        print("手部姿态分类模型初始化失败: \(error.localizedDescription)")
        return nil
    }
}()

如果需要确保模型加载成功才启动相关功能,也可以在功能启动前置阶段完成初始化:

private var model: VNCoreMLModel?

override func viewDidLoad() {
    super.viewDidLoad()
    setupMLModel()
}

private func setupMLModel() {
    do {
        let digitsModel = try Digits(configuration: .init())
        self.model = try VNCoreMLModel(for: digitsModel.model)
        // 模型加载成功后再启动手部姿态检测逻辑
        startHandPoseDetection()
    } catch {
        // 可弹出提示告知用户当前功能不可用
        showModelLoadErrorAlert()
    }
}

注意点

  • 不要直接在存储属性的初始化位置调用可能抛出错误的初始化方法,Swift不允许属性初始化阶段抛出未捕获的错误
  • 错误处理阶段可根据业务需要添加兜底逻辑,比如使用内置的基础姿态识别规则,避免功能直接不可用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 08:36:03