gpt4 book ai didi

ios - (Swift 3)父子上下文崩溃核心数据(libc++abi.dylib : terminating with uncaught exception of type NSException (Recorded Frame) )

转载 作者:行者123 更新时间:2023-11-28 12:39:34 25 4
gpt4 key购买 nike

我正在尝试将消息保存在后台队列中,并通过使用两个上下文(父项和子项)将它们推送到主队列。但我的应用程序不断崩溃。我使用了 apples docs,不知道为什么它不起作用......

Core Data, Multithreading, and the Main Thread

这是我的代码:

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

let privateMOC = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)


let doubletimestamp = Double(timestamp)
let date = Date(timeIntervalSinceReferenceDate: (doubletimestamp))
let status = "..."

let message = NSEntityDescription.insertNewObject(forEntityName: "Mesages", into: self.privateMOC) as! Mesages
message.text = text
message.timestamp = date as NSDate

do {
try self.privateMOC.save()
self.inputToolbar.toggleSendButtonEnabled()

self.context.performAndWait {

do {
try self.context.save()
} catch {
fatalError("Failure to save context: \(error)")
}

}

}catch let err {
print(err)
}

}

这也是我的堆栈跟踪: enter image description here

最佳答案

好吧,你有两个问题。

首先是你没有设置父上下文。如果您不这样做,则不会将任何内容传播到您的主要托管上下文

第二个是您没有在它自己的 block 中更改私有(private)托管上下文。就像您的正常托管上下文需要运行(您已经完成)一样,私有(private)上下文也需要执行相同的操作。

所以完成的代码应该是这样的:-

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

let privateMOC = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)

private.parentContext = context

let doubletimestamp = Double(timestamp)
let date = Date(timeIntervalSinceReferenceDate: (doubletimestamp))
let status = "..."

privateMOC.performBlock {

let message = NSEntityDescription.insertNewObject(forEntityName: "Mesages", into: self.privateMOC) as! Mesages
message.text = text
message.timestamp = date as NSDate

do {
try self.privateMOC.save()
self.inputToolbar.toggleSendButtonEnabled()

self.context.performAndWait {

do {
try self.context.save()
} catch {
fatalError("Failure to save context: \(error)")
}

}

}catch let err {
print(err)
}

}
}

关于ios - (Swift 3)父子上下文崩溃核心数据(libc++abi.dylib : terminating with uncaught exception of type NSException (Recorded Frame) ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39809670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com