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.
In order to get an array of dictionaries from the fetch request you must do two things:
fetchRequest.resultType = .dictionaryResultType
(as you already did), andNSFetchRequest<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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With