Home > Enterprise >  Fetch all core data objects for entity in a variable in struct
Fetch all core data objects for entity in a variable in struct

Time:11-06

I previously used swiftui to get objects using @ FetchRequest and stored all the objects of an entity in a var. Now I want to do this in a non-ui file and I can't use @fetchrequest outside of a swiftui file and I can't find an alternative method.

I want to store all objects of Order entity in var orders in OrdersState struct.

struct OrdersState: Equatable {
    var orders = ?
}

for example I need to access objects of this Order entity like this :

OrdersState.orders[0].id

CodePudding user response:

You can use NSFetchRequest, like this:

struct OrdersState: Equatable {
    var orders: [Order] {
        let moc = PersistenceController.shared.container.viewContext // This is an example, use your managed object context

        let request = NSFetchRequest<Order>(entityName: "Order")
        
        return (try? moc.fetch(request)) ?? []
    }
}

In case you are unfamiliar with using the managed object context as shown above, the standard implementation that Xcode proposes for new projects is:

import CoreData

struct PersistenceController {
    static let shared = PersistenceController()

    let container: NSPersistentContainer

    init() {
        container = NSPersistentContainer(name: "NameOfYourCoreDataContainer")   // <-- Replace this string with the name of your Core Data container

        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        container.viewContext.automaticallyMergesChangesFromParent = true
    }
}

Adding this struct to your code should make it work properly, unless there are conflicts with the existing code.

  • Related