39

I have a view showing messages in a team that are filtered using @Fetchrequest with a fixed predicate '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)
                }
            }...

I want to make this predicate dynamic so that when the user switches team the messages of that team are shown. The code below gives me the following error

Cannot use instance member 'teamName' within property initializer; property initializers run before 'self' is available

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

...

I can use some help with this, so far I'm not able to figure this out on my own.

user1242574
  • 1,257
  • 3
  • 12
  • 29

6 Answers6

40

had the same problem, and a comment of Brad Dillon showed the solution:

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))

    }

in this example, you can modify the predicate in the initializer.

Antoine Weber
  • 1,741
  • 1
  • 14
  • 14
  • 1
    Can verify this solution works. It takes a little bit of doing on your end (I had to pass through strings of user entered data through the Struct call), but almost verbatim this code will plug in with very little, if any, modifications. When you're looping out the results, just use the FetchRequest var (wordsRequest in this instance) like any other ForEach and pull the entity attributes you want. btw, I'm using this solution with multiple entities and creating a view for each entity. Then I call the structs on a default view and pass the necessary vars to get the Core Data from all. – Trapp Jan 21 '20 at 02:40
  • Doesn't this cause a new fetch to be executed every single time any state changes? – malhal Aug 30 '20 at 21:18
  • 6
    this ain't gonna work if you want to receive updates as you get with @FetchRequest when entity data changes – Silviu St Nov 07 '20 at 19:49
31

With SwiftUI it is important that the View struct does not appear to be changed otherwise body will be called needlessly which in the case of @FetchRequest also hits the database. SwiftUI checks for changes in View structs simply using equality and calls body if not equal, i.e. if any property has changed. On iOS 14, even if @FetchRequest is recreated with the same parameters, it results in a View struct that is different thus fails SwiftUI's equality check and causes the body to be recomputed when normally it wouldn’t be. @AppStorage and @SceneStorage also have this problem so I find it strange that @State which most people probably learn first does not! Anyway, we can workaround this with a wrapper View with properties that do not change, which can stop SwiftUI's diffing algorithm in its tracks:

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)")
        }
    }
}

Edit: it might be possible to achieve the same thing using EquatableView instead of the wrapper View to allow SwiftUI to do its diffing on the teamName only and not the FetchRequest var. More info here: https://swiftwithmajid.com/2020/01/22/optimizing-views-in-swiftui-using-equatableview/

malhal
  • 26,330
  • 7
  • 115
  • 133
  • 2
    This seems like the most idiomatic solution. – jonlambert Nov 19 '20 at 08:27
  • this is it. Should be the answer. – zumzum Aug 12 '21 at 21:20
  • 1
    This answer fulfils the recommended structure (by Apple) to break up SwiftUI views into many small components. In doing so, this answer also breaks out the properties that are used in the SwiftUI diffing algorithm (as noted in the article by Majid) and therefore the fetch request calls are minimised. I applied this structure to one of my lists (with `@SectionedFetchRequest`) and noted faster rendering and also eliminated the problems I was experiencing with the .searchable modifier. – andrewbuilder Sep 09 '21 at 14:14
  • I would like to provide some tips for this. FetchRequest should be created with this parameter: "entity: NSEntityDescription.entity(forEntityName: "Your Entity", in: managedObjectContext)", otherwise some errors would come up. – Li Fumin Nov 16 '22 at 15:50
12

May be a more general solution for dynamically filtering @FetchRequest.

1、Create custom 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、how to use

//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
    }
}

In this way, you can dynamic change your NSPredicate or NSSortDescriptor.

yue Max
  • 219
  • 4
  • 4
  • If any other state changes causing the body to be recomputed a new fetch will be performed too! – malhal Aug 30 '20 at 21:19
10

Modified @FKDev answer to work, as it throws an error, I like this answer because of its cleanliness and consistency with the rest of SwiftUI. Just need to remove the parentheses from the fetch request. Although @Antoine Weber answer works just the same.

But I am experience an issue with both answers, include mine below. This causes a weird side effect where some rows not related to the fetch request animate off screen to the right then back on screen from the left only the first time the fetch request data changes. This does not happen when the fetch request is implemented the default SwiftUI way.

UPDATE: Fixed the issue of random rows animating off screen by simply removing the fetch request animation argument. Although if you need that argument, i'm not sure of a solution. Its very odd as you would expect that animation argument to only affect data related to that fetch request.

@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)
}
Eye of Maze
  • 1,327
  • 8
  • 20
  • Does it work? I cannot create NSPredicate by using self in init – Michał Ziobro Dec 09 '19 at 14:49
  • Yes. I'm not sure I understand what you mean. I did not use self to create a NSPredicate in init. self is only used to assign it to the @FetchRequest var, but you need to make sure you use the underscore after self, like this `self._varName` – Eye of Maze Dec 15 '19 at 11:13
  • This is the best answer I can find anywhere online. Thanks a lot! – thegathering Feb 14 '20 at 02:06
  • 1
    Expression type 'NSPredicate' is ambiguous without more context – gurehbgui Feb 24 '20 at 11:57
  • This solution is actually the best, as it keeps a FetchRequest. Doing a manual fetch in the init only will not update the view on CoreData changes. This does! Perfect answer – davidev Jun 30 '20 at 07:58
  • This option throw two errors 1: `Variable 'self.teamName' used before being initialized` 2: `Return from initializer without initializing all stored properties` – Patrik Spišák Aug 01 '20 at 10:50
  • Your solution, which I like very much, gives me the error `Variable 'self.messages' used before being initialized` in the line `predicate = NSPredicate (format:" team.name ==% @ ", teamName)`. Could you complete the example so that I can test it, why don't I understand how I can get rid of the error? – Cesare Piersigilli Jan 02 '21 at 17:19
  • @OMiiNiiZE For me, I added inited the Binding in init like init(by: Binding – Legolas Wang Jan 08 '21 at 03:04
  • For me, I added the Binding in init like init(teamName: Binding) { self._ teamName = teamName }. However, when doing so, the rest of the code will report "self._messages" used before initialized. This solution seems like a paradox for me without a way to populate data into the @Binding, may I ask if I use it wrong? Thank you! – Legolas Wang Jan 08 '21 at 03:10
8

Another possibility is:

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)
}

...
FKDev
  • 2,266
  • 1
  • 20
  • 23
  • For me this resulted in the following compiler error: `Cannot invoke initializer for type 'FetchRequest<_>' with no arguments` – Menno Nov 05 '19 at 11:38
  • you need to remove the (), but anyway I'm getting the error: Expression type 'NSPredicate' is ambiguous without more context – gurehbgui Feb 24 '20 at 12:00
5

I just had a similar problem, and am finding FetchRequest.Configuration helpful. Given this from the original code

@Binding var teamName: String

@FetchRequest(
    sortDescriptors: [NSSortDescriptor(keyPath: \Message.createdAt, ascending: true)],
    predicate: NSPredicate(format: "team.name == %@", "Developers"),
    animation: .default) var messages: FetchedResults<Message>

and, e.g., a TextField that binds to teamName, you can add an onChange handler that changes the predicate for messages:

TextField("Team Name", text: $teamName)
    .onChange(of: teamName) { newValue in
        messages.nsPredicate = newValue.isEmpty
        ? nil
        : NSPredicate(format: "team.name == %@", newValue)
    }

For more info see the docs for SwiftUI's FetchRequest.Configuration and in particular the section labelled Set configuration directly.

Mitch Chapman
  • 71
  • 1
  • 2