解码为NSManagedObject对象后需要获取请求

问题描述 投票:0回答:1

我有以下通用功能:它正确地创建了对象,我知道它被保存到核心数据中,因为如果之后立即执行获取请求,我会得到刚刚创建的对象。但是,对象本身不是有效的核心数据对象(x-core数据错误)。有没有办法,所以我不必在解码对象后立即进行获取请求?非常感谢。

func decode<T: Decodable>(data: Data?, objectType: T.Type, save: Bool = true, completionHandler: @escaping (T) -> ())
{
    guard let d = data else { return }
    do
    {
        let privateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
        privateContext.parent = SingletonDelegate.shared.context

        let root = try JSONDecoder(context: privateContext).decode(objectType, from: d)

        if save
        {
            try privateContext.save()
            privateContext.parent?.performAndWait
            {
                do
                {
                    if let p = privateContext.parent
                    {
                        try p.save()
                    }

                }catch
                {
                    print(error)
                }
            }
        }
        DispatchQueue.main.async
        {
            completionHandler(root)
        }
    }catch
    {
        print(error)
    }
}

extension CodingUserInfoKey 
{
    static let context = CodingUserInfoKey(rawValue: "context")!
}


extension JSONDecoder 
{
    convenience init(context: NSManagedObjectContext) 
    {
        self.init()
        self.userInfo[.context] = context
    }
}
ios swift nsmanagedobject decodable
1个回答
0
投票

核心数据错误是有效的核心数据对象;它还没有从后备存储器检索到内存中。

为减少内存使用,Core Data仅在您访问其中一个属性时获取完整对象。此提取是自动的,对您的代码有效透明。

这意味着你不需要做任何特别的事情;你可以使用托管对象。

© www.soinside.com 2019 - 2024. All rights reserved.