带扩展的 Swift3 CoreData

Swift3 CoreData with Extension

我正在使用扩展处理核心数据,但出现以下错误。

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'executeFetchRequest:error: is not a valid NSFetchRequest.'

它在主机应用程序上仍然运行良好,但在使用相同代码的扩展程序上崩溃。

调试器在执行时停止 managedObjectContext.fetch(请求)

func getDataString() -> String {

    var result = ""

    let entityDescription = NSEntityDescription.entity(forEntityName: "DataString", in: managedObjectContext)!
    let request : NSFetchRequest<NSFetchRequestResult> = DataString.fetchRequest()
    request.entity = entityDescription

    do {
        let results = try managedObjectContext.fetch(request)
        printDebug(message: "\tDataString Count : \(results.count)")

        if results.count > 0 {
            let row = results[0] as! NSManagedObject

            result = row.value(forKey: "data") as! String
        }
    } catch let error {
        printDebug(message: "ERROR : getDataString fetch")
        setErrorLog(errorText: "\(error)")
    }

    return result
}

即使使用 try-catch 编写也会崩溃。 请帮忙

您的 NSFetchRequest 的通用类型必须是 DataString:

let request: NSFetchRequest<DataString> = DataString.fetchRequest()

managedObjectContext.perform {
    do {
        let results = request.execute()
    } catch let error {
        ...
    }
}

自己回答。

func getDataString() -> String {

var result = ""

let request = NSFetchRequest<NSFetchRequestResult>(entityName: "DataString")

do {
    let results = try managedObjectContext.fetch(request)
    printDebug(message: "\tDataString Count : \(results.count)")

    if results.count > 0 {
        let row = results[0] as! NSManagedObject

        result = row.value(forKey: "data") as! String
    }
} catch let error {
    printDebug(message: "ERROR : getDataString fetch")
    setErrorLog(errorText: "\(error)")
}

return result }

这有效。