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

9
我试图将我的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
 }

我查看了这个问题:如何将NSManagedObject转换为NSDictionary,但他们的方法似乎与我的非常不同。我也尝试了这个问题中提供的方法:在Swift 3中将CoreData对象转换为JSON。然而,我收到了以下错误:

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

我似乎找不到解决方法。

这个错误之前在这里提到过:Core Data:无法将类型'MyType_MyType_2'的值强制转换为MyType,但是没有哪种方法可以解决我的问题。有人能为我提供一个Swift解决方案吗?

更新

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

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

记录+核心数据类:

public class Record: NSManagedObject {

}

记录+核心数据特性:

extension Record {

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

    @NSManaged public var name: String?

}

这里定义了records

records 在哪里定义的?它是如何定义的?- 当 resultType = .dictionaryResultType 时,获取请求返回一个由字典组成的数组,这与你的返回类型 [Record] 不兼容。 - Martin R
请查看我在问题上的更新。 - Chace
你想要一个记录对象数组还是一个字典数组? - Martin R
我认为我需要一个字典数组来将它们序列化为JSON?也许我错了。 - Chace
1个回答

19

为了从fetch请求中获得一个字典数组,您需要执行两个操作:

  • 设置fetchRequest.resultType = .dictionaryResultType(就像您已经做的那样),以及
  • 将fetch请求声明为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)
}

现在records的类型为[NSDictionary],它将包含获取到的对象的字典表示的数组。


1
谢谢您,我的数据现在以字典的形式打印出来了。然而,它改变了我显示数据的方式,因为它不再使用“Record”类,而是使用“NSDictionary”。如何最好地使我的数据像以前一样显示? - Chace
1
@Chace:我会使用单独的获取请求。一个(带有NSFetchedResultsController)用于在表视图中显示数据,另一个用于导出数据。 - Martin R
很好的解释。救了我的一天,或者我应该说是“晚上”。谢谢 :) - sugarakis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接