use*_*574 8 core-data nspredicate nsfetchrequest swift swiftui
我有一个视图,显示团队中使用@Fetchrequest和固定谓词“开发人员”过滤的消息。
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)
}
}...
Run Code Online (Sandbox Code Playgroud)
我想使该谓词动态化,以便在用户切换团队时显示该团队的消息。下面的代码给我以下错误
无法在属性初始化程序中使用实例成员'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
...
Run Code Online (Sandbox Code Playgroud)
我可以为此提供一些帮助,但到目前为止我还无法自行解决。
mal*_*hal 17
对于 SwiftUI,重要的是 View 结构不会被更改,否则主体将被不必要地调用,在这种情况下@FetchRequest也会访问数据库。SwiftUI 仅使用相等检查视图结构中的更改,如果不相等则调用 body,即,如果任何属性已更改。在 iOS 14 上,即使@FetchRequest使用相同的参数重新创建,也会导致视图结构不同,因此无法通过 SwiftUI 的相等性检查,并导致在正常情况下重新计算主体。@AppStorage并且@SceneStorage也有这个问题,所以我觉得很奇怪,@State大多数人可能先学习的东西没有!无论如何,我们可以使用属性不变的包装器 View 来解决这个问题,这可以阻止 SwiftUI 的差异算法在其轨道上运行:
struct ContentView: View {
@State var teamName "Team" // source of truth, could also be @AppStorage if would like it to persist between app launches.
@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 {
let 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)")
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:有可能使用EquatableView代替包装器来实现相同的事情,View以允许 SwiftUI 对teamName唯一而不是FetchRequestvar进行差异处理。更多信息在这里:https :
//swiftwithmajid.com/2020/01/22/optimizing-views-in-swiftui-using-equatableview/
Syb*_*Syn 10
修改后的@FKDev 答案可以工作,因为它会引发错误,我喜欢这个答案,因为它与 SwiftUI 的其余部分保持一致。只需要从 fetch 请求中删除括号。虽然@Antoine Weber 的回答是一样的。
但是我在这两个答案中都遇到了问题,请在下面包含我的答案。这会导致一个奇怪的副作用,其中一些与 fetch 请求无关的行在屏幕上向右移动,然后仅在 fetch 请求数据第一次更改时从左侧返回屏幕。当以默认的 SwiftUI 方式实现获取请求时,不会发生这种情况。
更新: 通过简单地删除获取请求动画参数来修复屏幕外随机行动画的问题。虽然如果你需要那个论点,我不确定一个解决方案。它非常奇怪,因为您期望动画参数仅影响与该获取请求相关的数据。
@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)
}
Run Code Online (Sandbox Code Playgroud)
另一种可能是:
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)
}
...
Run Code Online (Sandbox Code Playgroud)
有同样的问题,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))
}
Run Code Online (Sandbox Code Playgroud)
在此示例中,您可以在初始化程序中修改谓词。
小智 7
可能是动态过滤@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
}
}
Run Code Online (Sandbox Code Playgroud)
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
}
}
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您可以动态更改您的 NSPredicate 或 NSSortDescriptor。
小智 5
我刚刚遇到了类似的问题,并且发现FetchRequest.Configuration很有帮助。从原始代码中可以看出这一点
@Binding var teamName: String
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Message.createdAt, ascending: true)],
predicate: NSPredicate(format: "team.name == %@", "Developers"),
animation: .default) var messages: FetchedResults<Message>
Run Code Online (Sandbox Code Playgroud)
并且,例如,绑定到 的 TextField teamName,您可以添加一个onChange处理程序来更改 的谓词messages:
TextField("Team Name", text: $teamName)
.onChange(of: teamName) { newValue in
messages.nsPredicate = newValue.isEmpty
? nil
: NSPredicate(format: "team.name == %@", newValue)
}
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅 SwiftUI 的FetchRequest.Configuration的文档,特别是标记为直接设置配置的部分。
| 归档时间: |
|
| 查看次数: |
816 次 |
| 最近记录: |