【问题标题】:How To convert NSManagedObject to Decodable class in Core data Swift如何在核心数据 Swift 中将 NSManagedObject 转换为 Decodable 类
【发布时间】:2021-01-24 10:27:03
【问题描述】:

我收到了一些服务器响应,它类似于以下格式。

{
    "sample_id": "Sample 1",
    "token": 2,
    "data": [
        {
            "id": "2",
            "date": "Oct 20 2019"
        },
        {
            "id": "3",
            "date": "Oct 08, 2019"
        }
    ]
}

为此,我创建了实体并将 attribute 声明为 Transformable 类型。

 static func fetchInfo() -> [Info] {
        
        // Create Fetch Request
        let managedContext = someMethod.getContext()
        let fetchRequest =  NSFetchRequest<NSFetchRequestResult>(entityName: "Entity")

        var result = [Info]()
        do {
            // Execute Fetch Request
            let records = try managedContext.fetch(fetchRequest)
            if let records = records as? [Info] {
                result = records
            }
        }catch {
            print("Unable to fetch managed objects for entity \(String(describing: entity)).")
        }
        return result
    }

但是,在上述方法中,它不会进入 记录 并且数据没有分配给模型(可解码)类。

我的可解码类是

struct Info: Decodable {
    
    let sampleId: String?
    let token: Int?
    let data: [Data]?
    
    enum CodingKeys: String, CodingKey {
        case sampleId = "sample_id"
        case token = "surveys_taken"
        case data = "data"
        
    }
    
}

struct Data: Decodable {
    
    let id: String?
    let date: String?
    
    enum CodingKeys: String, CodingKey {
        case id = “id”
        case date = “date”
    }
}

有什么建议吗?

【问题讨论】:

  • 不要将自定义类型命名为与内置类型相同的名称,因此请将 Data 重命名为其他名称。而且您不能只将 NSManagedObject 的子类转换为您的 struct Info,您需要一些代码在两者之间进行映射。也许您可以将保存信息的代码添加到您的商店中
  • 我刚刚根据隐私提供了实体名称示例

标签: ios swift xcode core-data nsmanagedobject


【解决方案1】:

尝试像这样测试

let fetchRequest: NSFetchRequest<Info> = Info.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "self == %@", self.objectID)
do {
    let result = try context.fetch(fetchRequest)
    if let info = result.first {
         return info
    }
} catch {
    print("Failed to fetch Info: \(error)", module: coreDataLogModule)
}

return self

【讨论】:

  • 什么是 INOLogError?而且 Info 是一个结构体,而不是 NSManagedObject 的子类
  • @developer 没有 objectiid 属性,我有一个属性是 Transformable 类型
  • @AnilkumariOS-ReactNative 是的,如果 self 在这种情况下是一个 NSManagedObject 但这个答案似乎断章取义,所以很难知道。
  • 那么,如何将 nsmanagedObject 转换为 Model 类,有什么建议吗?
  • @AnilkumariOS-ReactNative 我们不知道要转换什么,因为我们不知道您在实体中存储的内容/方式。
猜你喜欢
  • 2017-02-06
  • 2017-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-06
  • 2015-05-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多