How To convert NSManagedObject to Decodable class in Core data Swift

Viewed 651

I am getting some server response and it is like below format.

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

and for this I have created Entity and declared attribute as Transformable type.

 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
    }

But, In above method its not going inside records and data not assigning to model (decodable) class.

And my decodable class is

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”
    }
}

Any suggestions?

1 Answers

try to test like this

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
Related