Xcode项目集成CoreML模型报错:Cannot call value of non-function type 'MLModel'
从TensorFlow Hub获取模型并转换为CoreML模型后,集成到Xcode项目构建时触发如下错误:
Cannot call value of non-function type 'MLModel'
错误出自Xcode自动生成的Swift文件中的两个load函数:
/** Construct model instance asynchronously with URL of the .mlmodelc directory with optional configuration. Model loading may take time when the model content is not immediately available (e.g. encrypted model). Use this factory method especially when the caller is on the main thread. - parameters: - modelURL: the URL to the model - configuration: the desired model configuration - handler: the completion handler to be called when the model loading completes successfully or unsuccessfully */ class func load(contentsOf modelURL: URL, configuration: MLModelConfiguration = MLModelConfiguration(), completionHandler handler: @escaping (Swift.Result<model, Error>) -> Void) { MLModel.load(contentsOf: modelURL, configuration: configuration) { result in switch result { case .failure(let error): handler(.failure(error)) case .success(let model): handler(.success(model(model: model))) } } } /** Construct model instance asynchronously with URL of the .mlmodelc directory with optional configuration. Model loading may take time when the model content is not immediately available (e.g. encrypted model). Use this factory method especially when the caller is on the main thread. - parameters: - modelURL: the URL to the model - configuration: the desired model configuration */ class func load(contentsOf modelURL: URL, configuration: MLModelConfiguration = MLModelConfiguration()) async throws -> model { let model = try await MLModel.load(contentsOf: modelURL, configuration: configuration) return model(model: model) }
已排查:检查过模型构建阶段、目标成员资格,清理过构建文件夹和Derived Data,但错误仍存在,求解决方向。
修复类名与变量名冲突
自动生成的模型类名是小写的model,和函数内的局部变量model重名,编译器混淆了类型构造和变量引用。这是因为你的.mlmodel文件名为model.mlmodel,Xcode默认用文件名作为类名。
解决:将.mlmodel文件重命名为大写开头的有意义名称(如ImageClassifier.mlmodel),Xcode会自动生成对应大写类名,彻底解决冲突。重新验证CoreML模型转换流程
转换过程中可能出现模型结构损坏,导致Xcode生成的代码异常。重新使用coremltools转换模型,确保转换无报错,且生成的.mlmodel能在Xcode中正常预览输入输出特征:import coremltools as ct import tensorflow_hub as hub # 加载TF Hub模型 tf_model = hub.load("https://tfhub.dev/...") # 转换为MLProgram格式(适配Xcode 13+) coreml_model = ct.convert(tf_model, convert_to="mlprogram") coreml_model.save("ImageClassifier.mlmodel")匹配Xcode与coremltools版本
高版本coremltools生成的MLProgram格式模型需要对应版本的Xcode支持:- coremltools 6.x → Xcode 13.x
- coremltools 7.x → Xcode 14.x
如果Xcode版本过低,会导致代码生成逻辑异常,升级Xcode或降低coremltools版本即可。
临时手动修正代码(不推荐)
若暂时无法重命名模型,可手动修改自动生成文件中的model(model: model)为实际模型类名(如ImageClassifier(model: model)),但注意Xcode重新生成代码时会覆盖该修改,仅作为临时应急方案。
内容的提问来源于stack exchange,提问作者RobotBoa

