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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.