swiftuinsfetchrequestfetchrequest

Loading CoreData in function SwiftUI, with NSFetchRequest Error


import SwiftUI
import Foundation
import CoreData

//MARK: - Welcome View
struct fetchView: View {
    
    
    //MARK: - View
    var body: some View {
        let testing = getFetch()
        ForEach(testing) {test in
            
        }
        Text("Hello World")
    }
    
    //MARK: - Methods
    
    func getFetch() -> NSFetchRequest<FeedList> {
        let fr: NSFetchRequest<FeedList> = NSFetchRequest<FeedList>(entityName: "timestamp")
        fr.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: true)]
        fr.predicate = NSPredicate(format: "timestamp > %@", Calendar.current.startOfDay(for: Date()) as NSDate)
        return fr
    }
}

//MARK: - Preview
struct fetchView_Previews: PreviewProvider {
    static var previews: some View {
        fetchView()
    }
}

In the Line ForEach(testing) (with the t of testing underlined red) I get the error

Cannot convert value of type 'NSFetchRequest' to expected argument type 'Range'

If someone knows how to fix this so I can list out the data in my CoreData via. a function that would be a great help.

P.S. I know how to do a @fetchRequest but I am trying to do this so it works in a class where everyday I can total values and put them in an array and @fetchRequest only works in a struct.


Solution

  • You are returning the fetch request from that function. What you need to do is return the fetched result (array of type FeedList), by calling fetch function on managed object context and passing in the fetchRequest that you made.