【问题标题】:CoreStore creating object and return it in successCoreStore 创建对象并成功返回
【发布时间】:2019-09-15 08:14:00
【问题描述】:

我使用这段代码来创建一个对象:

CoreStore.perform(
            asynchronous: { (transaction) -> Void in
                let summary = transaction.create(Into<SummaryEntity>())

        },
            completion: { _ in }
        )

完成后我想返回刚刚创建的摘要对象。

如何做到这一点?

我做了类似的事情,但不确定我们需要大量解包和fetchExisting 函数

CoreStore.perform(
            asynchronous: { (transaction) -> Routine? in

                let routine = try! transaction.importUniqueObject(
                    Into<Routine>(),
                    source: routineDictionary)

                return routine
        },
            success: { (transactionRoutine) in

                guard let unwrappedTransactionRoutine = transactionRoutine else {
                    return
                }

                let routine = CoreStore.fetchExisting(unwrappedTransactionRoutine)

                guard let unwrappedRoutine = routine else {
                    return
                }

                completion(.data(unwrappedRoutine))
        },
            failure: { (error) in
                // ...
        }
        )

这是从fetchExisting展开的错误:

【问题讨论】:

    标签: ios swift core-data swift5 corestore


    【解决方案1】:

    我不确定你在问什么,因为你的例子完全不同。

    如果您想创建一个对象,您将执行与导入相同的操作。 transaction.create 不返回可选项,因此只需在第一个闭包中返回对象即可:

    CoreStore.perform(asynchronous: { (transaction) -> SummaryEntity in
        let summary = transaction.create(Into<SummaryEntity>())
        return summary
    }, success: { (summary) in
        let fetchedSummary = CoreStore.fetchExisting(summary)
        completion(.data(fetchedSummary))
    }, failure: { (error) in
        // ...
    })
    

    【讨论】:

    • 好的,谢谢!看起来我们仍然需要解开 fetchedSummary。我们需要使用CoreStore.fetchExisting 从主只读上下文中获取NSManagedObject 并且success: { (summary) in 从后台上下文中返回NSManagedObject 我对吗?
    • 是的正确,这也是我的观察,返回的项目来自背景上下文。所以你必须做 fetchExisting。我不知道你为什么需要打开它,因为 fetchExisting 不返回可选值。
    • 我添加了一个带有可选编译错误的图像。感谢您的帮助!
    • 好的,我明白了……我一直使用数组,它们确实是非可选的,但单次 fetch 返回可选。然后你需要做一个 if let 来解包,否则执行 completion(.error....) 类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2019-06-29
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 2014-07-07
    • 1970-01-01
    相关资源
    最近更新 更多