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

Swift保存布尔值到Core Data遇类型不匹配编译错误求助

Swift布尔值存入Core Data编译错误解决

错误信息

Thread 1: "Unacceptable type of value for attribute: property = "bool"; desired type = NSNumber; given type = __SwiftValue; value = true."

问题场景

尝试将布尔值保存到Core Data时触发上述编译错误,现有ViewController和CoredataHandler两个类,Core Data中User实体的bool属性类型为Boolean。

原代码

ViewController

class ViewController: UIViewController {
    
    var user : [User]? = nil
        CoredataHandler.saveObject(username: "Yahs", password: "213", bool: true)
}

CoredataHandler

class CoredataHandler : NSManagedObject {
    
    private class func getContext() -> NSManagedObjectContext {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
    
        return appDelegate.persistentContainer.viewContext
    }
    
    class func saveObject(username: String,password: String,bool: DarwinBoolean) -> Bool{
        let context = getContext()
        let entity = NSEntityDescription.entity(forEntityName: "User", in: context)
        let managedObject = NSManagedObject(entity: entity!, insertInto: context)
        
        managedObject.setValue(username, forKey: "username")
        managedObject.setValue(password, forKey: "password")
        managedObject.setValue(bool, forKey: "bool")
        
        do {
            try context.save()
            return true
        } catch{
            return false
        }
    }
}

问题原因

Core Data的Boolean属性底层依赖NSNumber类型存储,但saveObject方法中定义的bool参数类型是DarwinBoolean,传入Swift原生Bool值后会导致类型不匹配,触发错误。

修复方案

1. 修正参数类型

将CoredataHandler中saveObject方法的bool参数类型从DarwinBoolean改为Swift原生Bool,Swift的Bool会自动桥接为NSNumber,符合Core Data的要求。

2. 优化代码结构(可选但推荐)

  • CoredataHandler是工具类,不需要继承NSManagedObject
  • 使用Core Data生成的User托管对象子类,替代直接操作NSManagedObject,避免字符串key的拼写错误,提升类型安全性。

修改后的完整代码

CoredataHandler

class CoredataHandler {
    private class func getContext() -> NSManagedObjectContext {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        return appDelegate.persistentContainer.viewContext
    }
    
    class func saveObject(username: String, password: String, bool: Bool) -> Bool{
        let context = getContext()
        // 使用生成的User子类直接创建实例
        let user = User(context: context)
        user.username = username
        user.password = password
        user.bool = bool
        
        do {
            try context.save()
            return true
        } catch {
            print("保存失败:\(error.localizedDescription)")
            return false
        }
    }
}

ViewController

class ViewController: UIViewController {
    var user: [User]? = nil
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 将方法调用放到合适的生命周期方法中
        let isSaved = CoredataHandler.saveObject(username: "Yahs", password: "213", bool: true)
        print(isSaved ? "数据保存成功" : "数据保存失败")
    }
}

生成User托管子类方法

打开Core Data模型文件(.xcdatamodeld),选中User实体,点击菜单栏的Editor -> Create NSManagedObject Subclass...,按照向导完成子类生成即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:01:14