I am having trouble with a CoreData fetchRequest:
I am building an app that uses the BLE protocol to connect the iPhone with peripheral devices. The goal is to display saved peripheral devices and newly discovered devices in a View called DeviceListView.
DeviceListView is set up with two Lists, one for new devices, which pulls the newly discovered peripherals from a BLECentralManager file, and one for the saved peripherals which uses an instance of CoreDataController to fetch the devices saved in CoreData. The devices we’ve connected to are saved in Core Data (entity named: “Device”). The issue happens in my CoreDataController file:
import Foundation
import CoreData
import SwiftUI
class CoreDataController: ObservableObject {
static let shared = CoreDataController()
let persistentContainer: NSPersistentContainer
var fetchedDevices: FetchedResults<Device> // Property to hold fetched devices
init() {
persistentContainer = NSPersistentContainer(name: "Device")
persistentContainer.loadPersistentStores { (storeDescription, error) in
if let error = error {
print("Failed to load the data (error.localizedDescription)")
}
}
// Create a fetch request for Device entities
let fetchRequest: NSFetchRequest<Device> = Device.fetchRequest()
// Optionally, add sort descriptors if needed
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
fetchedDevices = FetchedResults<Device>(fetchRequest: fetchRequest, managedObjectContext: persistentContainer.viewContext)
}
func newDevice(latitude: Double, longitude: Double, name: String, serialNumber: String, context: NSManagedObjectContext) {
let device = Device(context: context)
device.setValue(latitude, forKey: "latitude")
device.setValue(longitude, forKey: "longitude")
device.setValue(name, forKey: "name")
device.setValue(serialNumber, forKey: "serialNumber")
save(context: context)
}
func save(context: NSManagedObjectContext) {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Handle errors here
fatalError("Unresolved error (error), (error.localizedDescription)")
}
}
}
}
The line: fetchedDevices = FetchedResults<Device>(fetchRequest: fetchRequest, managedObjectContext: persistentContainer.viewContext)
keeps throwing the error 'FetchedResults<Device>' cannot be constructed because it has no accessible initializers
.
I am not sure what the error means as far as “no accessible initializers”. I think I have provided everything that is needed. My guess is there is something in the syntax I have overlooked. It seems a lot of the questions on here regarding “no accessible initializers” deal more with UIKit, which I am not familiar with. I have tried to figure out the source of this issue, but I have no clue. Can anyone help me see something that I’m missing?
8