Search code examples
swiftcore-datansfetchrequest

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)


Solution

  • As we agreed I'm posting my core data functions, they may not be the best way but they work in my project. My entity is called Goals.

    // MARK: - Core data funcitons
    
    func loadCoreData(){
        goalsArray.removeAll()
    
        //let request = NSFetchRequest<Goals>(entityName:"Goals")
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    
    do{
    let fetchRequest : NSFetchRequest<Goals> = Goals.fetchRequest() as! NSFetchRequest<Goals>
    let sortDescriptor = NSSortDescriptor(key: "id", ascending: false)
    fetchRequest.sortDescriptors = [sortDescriptor]
    
    let result = try context.fetch(fetchRequest)
        for result in result {
            goalsArray.append(result)
            print("Fetched result goaltitle is \(result.goalTitle!)")
        }
        tableView.reloadData()
    
    print("I've fetched the results")
    }
    catch {
        fatalError("Sthh")
        }
    }
    
    
    
    func countCoreDataObjects()-> Bool{
               //let request = NSFetchRequest<Goals>(entityName:"Goals")
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    
        do{
            let fetchRequest : NSFetchRequest<Goals> = Goals.fetchRequest() as! NSFetchRequest<Goals>
            let result = try context.fetch(fetchRequest)
            if result.count == 0 {
                return false
            } else {return true
    
            }
        }
        catch {
            fatalError("Sthh")
        }
    
    }
    
    
    func saveToCD(object: goalClassForPassing){
    
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        let entity = NSEntityDescription.entity(forEntityName: "Goals", in: context)
        let goal = NSManagedObject(entity: entity!, insertInto: context) as! Goals
    
    
    
        goal.goalTitle = object.goalName
        goal.id = String(describing:Date())
        goal.imagePath = object.imagePath
    
        do {
            try context.save()}
        catch {
            fatalError("couldn't save to core data")
        }
    
    
        goal.id = String(describing: Date())
        goalObjectToSaveToCD?.id = String(describing: NSDate())
        print(goalObjectToSaveToCD?.goalTitle)
        print("Saved \(goal.goalTitle) - \(goal.id) - \(goal.imagePath) to Core Data")
        loadCoreData()
    }