How to Fetch entries from database using input parameter as key in predicate

I posted this question with error message as title. got no help.
I am programmer with 20 years experience. but new to Swift Programming. So sorry, my terminology could be different / misleading.

I am navigating to different page view based on user action.

NavigationLink {
DisplayView(input_parameter: dispTab, isNew: false)
}

dispTab is an Array or Row (1 line entry from a table). it has many attributes.

one of the attribute,
dispTab.itemKey is defined as UUID.

I wanted to use dispTab.itemKey and fetch entries from database table.

could you help me with the code, please.

Here is the code I used, but it is giving me errors.

@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
    sortDescriptors: [NSSortDescriptor(keyPath: \LabelsItem.date, ascending: false)],
    predicate: {
        guard let currentUserId = AppSession.shared.currentUserId else {
            return NSPredicate(value: false) 
        }
        return NSPredicate(format: "userId == %@ AND itemKey == %@", currentUserId as CVarArg, input_parameter.itemKey as CVarArg)
    }(), // Immediately invoke the closure
    animation: .default
) private var itab: FetchedResults<ItemTable>

When I can use currentUserId (Global Variable) with no issues.
I don't know why I can't use input_parameter.itemKey.

I am able to "display" every attribute from input_parameter. but i can't use it to fetch the entries.
Could you please help.

Error is:
Cannot use instance member 'input_parameter' within property initializer; property initializers run before 'self' is available

So you have a userId that is stored in AppSession singleton, and you are also getting an actionId using the view initializer, am I correct?
if thats the case first of all you can't access your View proprties inside the @FetchRequest because by the time that you view is trying to create that fetch request, View is not initialized yet!
the solution is to create your fetch request inside your view Initializer.
Since I have no experience in CoreData ( but I have used this trick with SwiftData) it has to work.
so take what I say with a grain of salt, but in general you need to move your FetchRequest inside your initializer:

@FetchRequest  private var itab: FetchedResults<ItemTable>
init(input_parameter: ItemTable, isNew: Bool){
 //Do your stuff in here
        let fetchedResults = FetchRequest(
                sortDescriptors: [NSSortDescriptor(keyPath: \LabelsItem.date, ascending: false)],
                predicate: {
                    guard let currentUserId = AppSession.shared.currentUserId else {
                        return NSPredicate(value: false)
                    }
                    return NSPredicate(format: "userId == %@ AND itemKey == %@", currentUserId as CVarArg, input_parameter.itemKey as CVarArg)
                }(),// Immediately invoke the closure
                                                
                animation: .default:
            )
        self._itab = fetchedResults

this trick should do :grinning_face:

1 Like

Hi Mohammad, thank you for your response. It helped to resolve the issue.
Initially, I thought it was a Swift programming question, but after your clarification about Core Data, I understand why it wasn't getting attention. I'll make sure to ask more relevant questions in the future. Thank you so much.