Tancredi Michael Busatta Tancredi Michael Busatta - 2 months ago 77
Swift Question

CoreData implementation swift 3

I'm having problems implementing coredata in my project. it seems to be able to save but not to fetch. here's the code

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Utente", in: context)
let item = NSManagedObject(entity: entity!, insertInto: context)
var utente: Profilo? = nil
let vc = CustomTabBarController() as UIViewController
let vc1 = LoginController() as UIViewController
// Configure Fetch Request

do {
let request: NSFetchRequest<NSFetchRequestResult> = Profilo.fetchRequest()
let result = try context.fetch(request) as Profilo
utente = result as Profilo
print()
if utente?.type != nil {
if utente?.type == "students"{
print("students")
present(vc, animated: true, completion: nil)
}
if utente?.type == "parents"{
print("parents")
present(vc, animated: true, completion: nil)

}
if utente?.type == "teachers"{
print("teachers")
present(vc, animated: true, completion: nil)

}
} else {
print("variable type empty")
present(vc1, animated: true, completion: nil)

}
} catch {
let fetchError = error as NSError
print(fetchError)
}


i also get the error on the result line:
cannot invoke 'fetch' with an argument list of type (NSFetchRequest)

Answer

The syntax is supposed to be

let request: NSFetchRequest<Profilo> = Profilo.fetchRequest()
let result = try context.fetch(request) as! [Profilo] // returns always an array.

Consider that the default initializers CustomTabBarController() and LoginController() won't work.