如何使用属性作为 FetchRequest 谓词的参数



我正在尝试在显示视图之前使用谓词选择数据库项目,并且需要传递属性,但我处于 catch-22 情况,因为该属性可能未初始化,产生消息: 不能在属性初始值设定项中使用实例成员"主题"; 属性初始值设定项在"self"可用之前运行

struct ShowInfo: View
{
@State var subject: Subject
@Environment(.managedObjectContext) var moc
@FetchRequest(entity: Info.entity(), sortDescriptors: [NSSortDescriptor(key: "title", ascending: true)],
predicate: NSPredicate(format: "subject.title == %@", $subject.title)
) var infos: FetchedResults<Info>
@State var size = UIScreen.main.bounds.width / 3
var body: some View
{
List
{
Text("Info").font(.system(size: 24)).foregroundColor(Color.green)
ForEach(infos, id: .infoid)
{ info in
ZStack
{
if info.subject == self.subject.title
{
NavigationLink(destination: EditInfoView(info: info))
{
HStack
{
Text(info.title!).frame(width: 150, height: 40).background(Color.blue).foregroundColor(Color.white).cornerRadius(10)
Text(info.value!)
}
}
}
}
}.onDelete(perform: deleteInfo)
}
}
}

在 SwiftUI View 中找到的答案@FetchRequest带有可以更改的变量的谓词本质上是正确的,但我发现事物在结构中出现的顺序对于避免一系列错误很重要。

我修改了我的代码如下...

struct ShowInfo: View
{
init (subject: Subject)
{
self.subject = subject
self.infoRequest = FetchRequest<Info>(entity: Info.entity(), sortDescriptors: [NSSortDescriptor(key: "title", ascending: true)],predicate: NSPredicate(format: "subject.title == %@", subject.title!))
}
@Environment(.managedObjectContext) var moc
var subject: Subject
var infoRequest: FetchRequest<Info>
var infos: FetchedResults<Info>{infoRequest.wrappedValue}

这清除了所有错误并允许应用程序正常工作。 当 init(( 在变量声明之后时,我遇到了与以前相同的错误以及其他错误。 编译器似乎对已经初始化的内容和尚未初始化的内容感到困惑。我不确定为什么为问题57871088显示的示例适用于其他人,而我的需要重新排列声明。

我认为上面的答案解决了我的问题,在这种情况下确实如此,但在另一种观点中,相同的方法产生了错误,声称我没有初始化 init 中的所有属性。 经过多次实验,我发现如果我注释掉@Environment语句,所有这些错误都会消失。当然,这为未定义的变量 moc 生成了错误,所以我注释掉了该代码以查看发生了什么,然后原始错误再次出现。很明显,编译器变得混乱了。有谁知道解决这个问题的方法?

这是我现在正在使用的代码:

struct EditSubjectView: View
{
init(subject: Subject)
{
self.subject = subject
self.formRequest = FetchRequest(entity: Field.entity(), sortDescriptors: [NSSortDescriptor(key: "sequence", ascending: true)], predicate: NSPredicate(format: "subjectid == %@", subject.subjectid!.description))
}
@Binding var subject: Subject
var formRequest: FetchRequest<Field>
var fields : FetchedResults<Field>{formRequest.wrappedValue}
@Environment(.managedObjectContext) var moc
var body: some View
{
return VStack
{
HStack
{
Text("Subject Title").padding(.leading)
//Spacer()
}
TextField(subject.title!, text: Binding($subject.title)!)
.padding(.all)
.background(Color(red: 239.0/255.0, green: 243.0/255.0, blue: 244.0/255.0, opacity: 1.0))
.cornerRadius(15)
Spacer()
Button("Save")
{
do
{
try self.moc.save()
}
catch
{
print(error.localizedDescription)
}
}.frame(width: 150, height: 30).background(Color.red).foregroundColor(Color.white).cornerRadius(15.0)
}.padding()
}
}

最新更新