Swift,GCD和CoreData错误:错误:NULL _cd_rawData但对象没有变成错误

时间:2016-07-28 14:50:23

标签: ios swift core-data grand-central-dispatch

我编写了一些代码,用于准备CoreData的异步数据。我已经按照互联网上的提示,但有时我得到以下错误: CoreData:错误:NULL _cd_rawData但对象没有变成错误

这是我的代码,它执行从核心数据中读取对象并抛出错误。

func getObject(forKey: String, answer: (Bool, NSObject?) -> ()) {
    let pMOC = initPrivateMOC()
    pMOC.performBlock({
        let fetchRequest = NSFetchRequest()

        let entityDescription = NSEntityDescription.entityForName("CacheObject", inManagedObjectContext: pMOC)

        fetchRequest.entity = entityDescription
        fetchRequest.predicate = NSPredicate(format: "identifier == %@", forKey)


        do {
            let result = try self.managedObjectContext?.executeFetchRequest(fetchRequest) as! [CacheObject]
            var answerObject:NSObject?
            if !result.isEmpty {
                if let coObject = result[0].object {
                    if let retrievedObject = NSKeyedUnarchiver.unarchiveObjectWithData(coObject) as? NSObject {
                        answerObject = retrievedObject
                    }
                }
            }
            answer(true, answerObject)
        } catch {
            answer(false, nil)
            fatalError("[CacheManager:getObject] -> Fehler beim Lesen von Daten")
        }
    })
}

if let coObject = result[0].object出现错误。以下是获取私人MOC的功能:

init() {
    let coreDataHandler = CoreDataHandler(identifier: "MK.SimpleCacheStore", ressource: "SimpleCache")
    self.managedObjectContext = coreDataHandler.getMOC()

}

func initPrivateMOC() -> NSManagedObjectContext {
    let pMOC = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
    pMOC.parentContext = self.managedObjectContext

    return pMOC
}

此外,来自上面一个类的调用可以通过for请求访问:

public func get(forKey: String, answer: (Bool, NSObject?) -> ()) {
    if let cam = cacheManager {
        if let cachedObj = cam.getObjectFromCache(forKey) {
            print("[SCManager:get] -> Objekt aus NSCache geladen")
            answer(true, cachedObj)
        } else {
            if let cdm = coreDataManger {
                dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), {
                    cdm.getObject(forKey, answer: {
                        success, data in
                        //Enable Entry in NSCache
                        if let cdData = data {
                            cam.saveObjectToCache(forKey, object: cdData)
                            print("[SCManager:get] -> Objekt nach nicht auffinden gecacht")
                        }
                        print("[SCManager:get] -> Objekt nicht in NSCache, deshalb aus CoreData")
                        answer(success, data)
                    })
                })
            }
        }
}

您是否知道问题或发现我实施GCD和CoreData的方式存在任何错误或问题,提示将非常有用。

1 个答案:

答案 0 :(得分:0)

我发现了问题,我没有在我的请求中添加私人MOC。所以解决方案是使用 pMOC 来实现 fetchRequest()