无法将'NSKnownKeysDictionary1'()类型的值转换为''()

Cha*_*ace 5 core-data ios swift

我正在尝试将我的NSManagedObject转换为字典,因此我可以使用序列化它来获取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
 }
Run Code Online (Sandbox Code Playgroud)

我已经讨论过这个问题:如何将NSManagedObject转换为NSDictionary,但它们的方法与我的方法非常不同.我还尝试了这个问题中提供的方法:CoreData对象到Swift 3中的JSON.但是我收到了这个错误

无法将'NSKnownKeysDictionary1'(0x108fbcaf8)类型的值转换为'iOSTest01.Record'(0x1081cd690)$

而我似乎无法找到解决方案.

此前已提到错误:核心数据:无法将"MyType_MyType_2"类型的值转换为MyType,但没有一种方法可以解决我的问题.有人能为我提供一个Swift解决方案吗?

更新

为了帮助下面的评论,我添加了以下内容:

var record: Record!
var records = [Record]()
Run Code Online (Sandbox Code Playgroud)

记录+ CoreDataClass:

public class Record: NSManagedObject {

}
Run Code Online (Sandbox Code Playgroud)

记录+ CoreDataProperties:

extension Record {

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

    @NSManaged public var name: String?

}
Run Code Online (Sandbox Code Playgroud)

这是records定义的地方.

Mar*_*n R 12

要从获取请求中获取字典数组,您必须执行以下两项操作:

  • 设置fetchRequest.resultType = .dictionaryResultType(就像你已经做过的那样),和
  • 声明获取请求NSFetchRequest<NSDictionary>而不是NSFetchRequest<YourEntity>.

例:

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)
}
Run Code Online (Sandbox Code Playgroud)

现在records有了类型[NSDictionary],并将包含一个数组,其中包含已获取对象的字典表示.