gpt4 book ai didi

swift - 确保核心数据 @FetchRequest 变量动态运行需要哪些代码更改(附加代码)?

转载 作者:行者123 更新时间:2023-11-30 10:33:28 26 4
gpt4 key购买 nike

我的代码应该如何修改,以确保当添加新项目时核心数据层发生异常时,SwiftUI 不会继续显示新项目?

背景:当我运行下面的代码时,在添加执行“context.save()”的新项目时出现异常,但是,虽然新项目请求确实失败了(没有保存到核心数据),但 UI 确实失败了显示一个新项目。就好像 @FetchRequest 行中的“lists”变量没有动态运行。

问题 - 如何修复代码以使应用程序正常工作?

代码:

import SwiftUI

struct ContentView: View {
@Environment(\.managedObjectContext) var context
@FetchRequest(fetchRequest: List.allListFetchRequest()) var lists: FetchedResults<List>

private func addListItem() {
let newList = List(context: context)
newList.id = 1
newList.title = "Testing 123"
do {
try context.save()
} catch let e as NSError {
print("Could not save new List. \(e.debugDescription)")
return
}

}

var body: some View {
NavigationView {
VStack {
ForEach(lists) { list in
Text("List = \(list.title)")
}
}
.navigationBarTitle( Text("My Todo Lists") )
.navigationBarItems(
trailing: Button(action: {self.addListItem()} ) {
Image(systemName: "plus.square")
}
)
}
}
}

示例输出:

Could not save new List. Error Domain=NSCocoaErrorDomain Code=133021 "(null)" UserInfo={NSExceptionOmitCallstacks=true, conflictList=(
"NSConstraintConflict (0x600001fcccc0) for constraint (\n id\n): database: (null), conflictedObjects: (\n \"0x600000a7e360 <x-coredata:///List/t2F01130C-0D2A-4E88-A77D-A7BA0E921C213>\",\n \"0xfb1bb528bb57810c <x-coredata://41B391F1-A95C-4971-9584-A2D3DFFF5380/List/p3>\"\n)"
)}

最佳答案

吉姆·多维 (Jim Dovey) 向我提出了这个建议:

private func addListItem() {  
context.performBlock { context in
let newList = List(context: context)
newList.id = 1
newList.title = "Testing 123"
do {
try context.save()
}
catch {
print("Failed to save new item. Error = \(error)")
context.delete(newList)
// don't need to save here, because we're in `performBlock` and have reverted the only unsaved change.
}
}
}

关于swift - 确保核心数据 @FetchRequest 变量动态运行需要哪些代码更改(附加代码)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58590556/

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