我有一个视图,显示团队中的消息,这些消息使用@Fetchrequest和固定谓词'Developers'进行过滤。
struct ChatView: View {
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Message.createdAt, ascending: true)],
predicate: NSPredicate(format: "team.name == %@", "Developers"),
animation: .default) var messages: FetchedResults<Message>
@Environment(\.managedObjectContext)
var viewContext
var body: some View {
VStack {
List {
ForEach(messages, id: \.self) { message in
VStack(alignment: .leading, spacing: 0) {
Text(message.text ?? "Message text Error")
Text("Team \(message.team?.name ?? "Team Name Error")").font(.footnote)
}
}...
我想使此谓词动态化,以便在用户切换团队时显示该团队的消息。下面的代码给我以下错误
不能在属性初始化程序中使用实例成员'teamName';属性初始化程序在“自我”可用之前运行
struct ChatView: View {
@Binding var teamName: String
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Message.createdAt, ascending: true)],
predicate: NSPredicate(format: "team.name == %@", teamName),
animation: .default) var messages: FetchedResults<Message>
@Environment(\.managedObjectContext)
var viewContext
...
我可以为此提供一些帮助,但到目前为止我还无法自行解决。
答案 0 :(得分:9)
有同样的问题,布拉德·狄龙(Brad Dillon)的评论显示了解决方案:
var predicate:String
var wordsRequest : FetchRequest<Word>
var words : FetchedResults<Word>{wordsRequest.wrappedValue}
init(predicate:String){
self.predicate = predicate
self.wordsRequest = FetchRequest(entity: Word.entity(), sortDescriptors: [], predicate:
NSPredicate(format: "%K == %@", #keyPath(Word.character),predicate))
}
在此示例中,您可以在初始化程序中修改谓词。
答案 1 :(得分:6)
可能是用于动态过滤@FetchRequest的更通用的解决方案。
1,创建自定义DynamicFetchView
import CoreData
import SwiftUI
struct DynamicFetchView<T: NSManagedObject, Content: View>: View {
let fetchRequest: FetchRequest<T>
let content: (FetchedResults<T>) -> Content
var body: some View {
self.content(fetchRequest.wrappedValue)
}
init(predicate: NSPredicate?, sortDescriptors: [NSSortDescriptor], @ViewBuilder content: @escaping (FetchedResults<T>) -> Content) {
fetchRequest = FetchRequest<T>(entity: T.entity(), sortDescriptors: sortDescriptors, predicate: predicate)
self.content = content
}
init(fetchRequest: NSFetchRequest<T>, @ViewBuilder content: @escaping (FetchedResults<T>) -> Content) {
self.fetchRequest = FetchRequest<T>(fetchRequest: fetchRequest)
self.content = content
}
}
2,使用方法
//our managed object
public class Event: NSManagedObject{
@NSManaged public var status: String?
@NSManaged public var createTime: Date?
... ...
}
// some view
struct DynamicFetchViewExample: View {
@State var status: String = "undo"
var body: some View {
VStack {
Button(action: {
self.status = self.status == "done" ? "undo" : "done"
}) {
Text("change status")
.padding()
}
// use like this
DynamicFetchView(predicate: NSPredicate(format: "status==%@", self.status as String), sortDescriptors: [NSSortDescriptor(key: "createTime", ascending: true)]) { (events: FetchedResults<Event>) in
// use you wanted result
// ...
HStack {
Text(String(events.count))
ForEach(events, id: \.self) { event in
Text(event.name ?? "")
}
}
}
// or this
DynamicFetchView(fetchRequest: createRequest(status: self.status)) { (events: FetchedResults<Event>) in
// use you wanted result
// ...
HStack {
Text(String(events.count))
ForEach(events, id: \.self) { event in
Text(event.name ?? "")
}
}
}
}
}
func createRequest(status: String) -> NSFetchRequest<Event> {
let request = Event.fetchRequest() as! NSFetchRequest<Event>
request.predicate = NSPredicate(format: "status==%@", status as String)
// warning: FetchRequest must have a sort descriptor
request.sortDescriptors = [NSSortDescriptor(key: "createTime", ascending: true)]
return request
}
}
通过这种方式,您可以动态更改NSPredicate或NSSortDescriptor。
答案 2 :(得分:6)
使用SwiftUI,重要的一点是不要更改View结构,否则将不必要地调用主体,在@FetchRequest
的情况下,主体也会命中数据库。 SwiftUI仅使用相等性检查View结构中的更改,如果不相等则调用body。在iOS 14中,即使使用相同的参数重新创建@FetchRequest
,它也会导致View结构不同,从而导致SwiftUI的相等性检查失败并导致不必要地重新计算主体。 @AppStorage
和@SceneStorage
也存在此问题,因此我感到奇怪的是,大多数人可能首先学习的@State
却没有!无论如何,我们可以使用具有不变属性的包装视图来解决此问题,这可以停止SwiftUI的差异算法在其轨迹中:
struct ContentView: View {
@State var teamName "Team"
@State var counter = 0
var body: some View {
VStack {
ChatView(teamName:teamName) // its body will only run if teamName is different, so not if counter being changed was the reason for this body to be called.
Text("Count \(counter)")
}
}
}
struct ChatView: View {
var teamName: String
var body: some View {
// ChatList body will be called every time but this ChatView body is only run when there is a new teamName so that's ok.
ChatList(messages: FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Message.createdAt, ascending: true)], predicate: NSPredicate(format: "team.name = %@", teamName)))
}
}
struct ChatList : View {
@FetchRequest var messages: FetchedResults<Message>
var body: some View {
ForEach(messages) { message in
Text("Message at \(message.createdAt!, formatter: messageFormatter)")
}
}
}
答案 3 :(得分:3)
另一种可能性是:
struct ChatView: View {
@Binding var teamName: String
@FetchRequest() var messages: FetchedResults<Message>
init() {
let fetchRequest: NSFetchRequest<Message> = Message.fetchRequest()
fetchRequest.sortDescriptors = NSSortDescriptor(keyPath: \Message.createdAt, ascending: true)
fetchRequest = NSPredicate(format: "team.name == %@", teamName),
self._messages = FetchRequest(fetchRequest:fetchRequest, animation: .default)
}
...
答案 4 :(得分:1)
修改后的@FKDev答案可以正常工作,因为它会引发错误,我喜欢这个答案,因为它的简洁性和与SwiftUI其余部分的一致性。只需从获取请求中删除括号即可。尽管@Antoine Weber的答案是一样的。
但是我在两个答案上都遇到了问题,请在下面列出。这会导致一个奇怪的副作用,即与获取请求无关的某些行会在屏幕外向右移动,然后仅在第一次获取请求数据发生更改时才从左向屏幕重新显示。当以默认的SwiftUI方式实现获取请求时,不会发生这种情况。
更新: 通过简单地删除获取请求动画参数,解决了随机行在屏幕外动画的问题。尽管如果您需要该参数,我不确定是否有解决方案。正如您所期望的那样,animation参数只会影响与该提取请求相关的数据。
@Binding var teamName: String
@FetchRequest var messages: FetchedResults<Message>
init() {
var predicate: NSPredicate?
// Can do some control flow to change the predicate here
predicate = NSPredicate(format: "team.name == %@", teamName)
self._messages = FetchRequest(
entity: Message.entity(),
sortDescriptors: [],
predicate: predicate,
// animation: .default)
}