Last active
February 2, 2022 16:06
-
-
Save bsorrentino/653380b9f1ac98510e1a628d075297ce to your computer and use it in GitHub Desktop.
SwiftUI Dynamically Filtering FetchRequest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct DynamicFetchRequestView<T: NSManagedObject, Content: View>: View { | |
// That will store our fetch request, so that we can loop over it inside the body. | |
// However, we don’t create the fetch request here, because we still don’t know what we’re searching for. | |
// Instead, we’re going to create custom initializer(s) that accepts filtering information to set the fetchRequest property. | |
@FetchRequest var fetchRequest: FetchedResults<T> | |
// this is our content closure; we'll call this once the fetch results is available | |
let content: (FetchedResults<T>) -> Content | |
var body: some View { | |
self.content(fetchRequest) | |
} | |
// This is a generic initializer that allow to provide all filtering information | |
init( withPredicate predicate: NSPredicate, andSortDescriptor sortDescriptors: [NSSortDescriptor] = [], @ViewBuilder content: @escaping (FetchedResults<T>) -> Content) { | |
_fetchRequest = FetchRequest<T>(sortDescriptors: sortDescriptors, predicate: predicate) | |
self.content = content | |
} | |
// This initializer allows to provide a complete custom NSFetchRequest | |
init( withFetchRequest request:NSFetchRequest<T>, @ViewBuilder content: @escaping (FetchedResults<T>) -> Content) { | |
_fetchRequest = FetchRequest<T>(fetchRequest: request) | |
self.content = content | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Dynamically Filtering FetchRequest
Refers to the article here