42

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.

8 Answers 8

39

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
Doesn't this cause a new fetch to be executed every single time any state changes?
this ain't gonna work if you want to receive updates as you get with @FetchRequest when entity data changes
33

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

4 Comments

This seems like the most idiomatic solution.
this is it. Should be the answer.
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.
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.
13

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.

1 Comment

If any other state changes causing the body to be recomputed a new fetch will be performed too!
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)
}

9 Comments

Does it work? I cannot create NSPredicate by using self in init
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
This is the best answer I can find anywhere online. Thanks a lot!
Expression type 'NSPredicate' is ambiguous without more context
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
|
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)
}

...

2 Comments

For me this resulted in the following compiler error: Cannot invoke initializer for type 'FetchRequest<_>' with no arguments
you need to remove the (), but anyway I'm getting the error: Expression type 'NSPredicate' is ambiguous without more context
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.

2 Comments

This is the only answer here that worked for me (Xcode 14.3, Swift 5.8)
This has a bug when if the view gets updated then the predicate will reset to the initial one. Now there is a mismatch between the displayed teamName and the results
0

I had the same issue and my preferred solution is an extension of your parent NSManagedObject which returns a FetchRequest for the child objects. In a simple example I have a parent entity Classroom and Student child entities which have One-to-One relationship inClassroom with a Classroom entity.

So I create an extension to Classroom that generates the FetchRequest for me:

extension Classroom {
    
    /// Returns a FetchRequest that fetches students in this classroom
    var fetchedStudents: FetchRequest<Student> {
        let predicate : NSPredicate = NSPredicate(format: "inClassroom = %@", self)
        return FetchRequest<Student>(entity: Student.entity(), sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)], predicate: predicate, animation: .default)
    }

}

And for your view which shows the child entities:

struct ClassroomView: View {
    
    @Environment(\.managedObjectContext) private var viewContext

    private var students: FetchRequest<Student>
        
    init(classroom: Classroom) {
        self.students = classroom.fetchedStudents
    }
    
    var body: some View {
        List(students.wrappedValue, rowContent: { student in
            Text(student.name ?? "Unnamed")
        })
    }
}

I'm sure there are better solutions out there but this one is clean and works for me.

Comments

0

Just a thought... assuming you aren't dealing with vast quantities of data, the simplest approach might simply be to get everything in your initial fetch request and then filter and sort the resulting array of objects.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.