0

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)

5
  • Can you post your save to core data please, I'm having trouble with it myself. Thanks ! Commented Sep 22, 2016 at 16:22
  • I just copied the answer below but now it doesn't work because i changed the model. I'm figuring out how to make it work again Commented Sep 28, 2016 at 14:21
  • I managed to make my coredata work so if you want I can post it as an answer here. Commented Sep 28, 2016 at 14:46
  • that would be great thank you!!!! Commented Sep 28, 2016 at 17:19
  • I posted my code as an answer below :) Commented Sep 28, 2016 at 18:39

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

The default initializer creates new empty instances of the controllers which are not the same as those designed in the Storyboard.
yeah but i'm not using the storyboard. Those are the views that i want to show if the conditions are satisfied. What would the sintax be?
Then you have to load the controllers from nib or create everything programmatically. Anyway the default initializer will not work. But that's beyond the scope of the question.
1

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()
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.