Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not cast value of type 'NSKnownKeysDictionary1' () to '' ()

I'm attempting to convert my NSManagedObject into a Dictionary so I can use serialize it for JSON.

func fetchRecord() -> [Record] {

        let fetchRequest = NSFetchRequest<Record>(entityName:"Record")
        let context = PersistenceService.context

        fetchRequest.resultType = .dictionaryResultType

        do {
            records = try context.fetch(Record.fetchRequest())

        } catch {
            print("Error fetching data from CoreData")
        }
        print(records)
        return records
 }

I have loked at this question: How to convert NSManagedObject to NSDictionary but their method appears very different to mine. I have also attempted the methods provided in this question: CoreData object to JSON in Swift 3. However I am receiving this error

Could not cast value of type 'NSKnownKeysDictionary1' (0x108fbcaf8) to 'iOSTest01.Record' (0x1081cd690)$

and I can't seem to find the solution.

The error has been mentioned before here: Core Data: Could not cast value of type 'MyType_MyType_2' to MyType but none of the methods are resolving my issue. Could anyone provide me a Swift solution for this?

Update

To help the comment below I have added the following:

var record: Record!
var records = [Record]()

Record+CoreDataClass:

public class Record: NSManagedObject {

}

Record+CoreDataProperties:

extension Record {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Record> {
        return NSFetchRequest<Record>(entityName: "Record")
    }

    @NSManaged public var name: String?

}

This is where records are defined.

like image 353
Chace Avatar asked Sep 20 '17 09:09

Chace


Video Answer


1 Answers

In order to get an array of dictionaries from the fetch request you must do two things:

  • Set fetchRequest.resultType = .dictionaryResultType (as you already did), and
  • declare the fetch request as NSFetchRequest<NSDictionary> instead of NSFetchRequest<YourEntity>.

Example:

let fetchRequest = NSFetchRequest<NSDictionary>(entityName:"Event")
fetchRequest.resultType = .dictionaryResultType

// Optionally, to get only specific properties:
fetchRequest.propertiesToFetch = [ "prop1", "prop2" ]

do {
    let records = try context.fetch(fetchRequest)
    print(records)
} catch {
    print("Core Data fetch failed:", error.localizedDescription)
}

Now records has the type [NSDictionary] and will contain an array with dictionary representations of the fetched objects.

like image 163
Martin R Avatar answered Oct 16 '22 05:10

Martin R