UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

FetchRequest conversion in SwiftUI

Forums > SwiftUI

How to convert a FetchRequest to an array within a View init() method? Thanks for help.

3      

You can try and map it:

var myArray: [ObjectType] = []

init(...) {
    fetchRequest = FetchRequest<MyObject>(
        entity: MyObject.entity(),
        sortDescriptors: [NSSortDescriptor(key: "order", ascending: true)],
        predicate: NSPredicate(format: "%K == %@", "someObject.id",  myPassedObject.id.uuidString)
    )
    myArray = myObject.map { $0 }
}

.. I've only done it like this before, though, when I am creating the fetchRequest within the init itself (i.e. not the @FetchRequest property wrapper), as shown. I've found it easier to extend the CoreData object itself and add a computed property.

4      

This is taken from Donny Wals - Practical Core Data

Set up a file with

class StorageProvider {
    let persistentContainer: NSPersistentContainer

    init() {
        persistentContainer = NSPersistentContainer(name: "HelloCoreData")

        persistentContainer.loadPersistentStores { (description, error) in
            if let error = error {
                fatalError("Core Data store failed to load with error: \(error.localizedDescription)")
            }
        }
    }
}

Then you can add

func getAllMovies() -> [Movie] {
    let fetchRequest: NSFetchRequest<Movie> = Movie.fetchRequest()

    do {
        return try persistentContainer.viewContext.fetch(fetchRequest)
    } catch {
        print("Failed to fetch movies: \(error)")
        return []
    }
}

and at call site add

let storageProvider: StorageProvider
@State private var movies: [Movie] = []

then in the action movies = storageProvider.getAllMovies() eg a button

or

let storageProvider = StorageProvider()
let movies: [Movie]
init() {
    movies = storageProvider.fetchRecords()
}

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.