ioscore-dataswift2entityupdatemodel

Can't update an entity in swift 2


I have a problem to update entity record using swift 2, In my code I want to be able to select a value from picker view for example language and then store that value into core data but if it has stored before update that value.

all of my code works but my update code gives me app delegate error : enter image description here

This is my full code :

import UIKit
import CoreData

class secondViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    //Mark : initializing variables
    @IBOutlet var labelPassedData: UILabel!
    @IBOutlet var pickerView: UIPickerView!
    var toPass:String!

    //data source
    var languageDB = [NSManagedObject]()
    @IBOutlet weak var dbshow: UILabel!

    let managedContext = AppDelegate().managedObjectContext

    var languagePicker = ["فارسی","English","العربية"]



    override func viewDidLoad() {
        super.viewDidLoad()    
        pickerView = UIPickerView()

        pickerView.dataSource = self
        pickerView.delegate = self

        labelPassedData.text = languagePicker[0] //

        fetch("Language")
        let counter : Int = languageDB.count
        print (counter)
        let Language = languageDB[counter - 1]
        dbshow!.text = Language.valueForKey("lang") as? String

    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func numberOfComponentsInPickerView (pickerView : UIPickerView) -> Int{
        return 1
    }

    func pickerView(pickerView : UIPickerView , numberOfRowsInComponent component : Int) ->Int{
        return languagePicker.count
    }

    func pickerView(pickerView : UIPickerView, titleForRow row:Int, forComponent component : Int) -> String?
    {
        return languagePicker[row]
    }

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){

        labelPassedData.text = languagePicker[row]

        self.Insert(labelPassedData!.text!) // calling save lang function


        let Language = languageDB[row]
        dbshow!.text = Language.valueForKey("lang") as? String

        self.view.endEditing(true)
    }



    func Insert(lang : String) {
        let check_empty = entityIsEmpty("Language")
        if(check_empty != true){

            let saveLanguage = NSEntityDescription.insertNewObjectForEntityForName("Language", inManagedObjectContext: managedContext)

            // add our data
            saveLanguage.setValue(lang, forKey: "lang")

            //2
            do {
                try managedContext.save()
                //3
                languageDB.append(saveLanguage)
            } catch let error as NSError  {
                print("Could not save \(error), \(error.userInfo)")
            }

        //check_empty
        }else{

            print ("update")
            let predicate = NSPredicate(format: "objectID == %@", "31")

            let fetchRequest = NSFetchRequest(entityName: "Language")
            fetchRequest.predicate = predicate

            do {
                let fetchedEntities = try self.managedContext.executeFetchRequest(fetchRequest) as! [Language]
                fetchedEntities.first?.lang = lang

                // ... Update additional properties with new values
            } catch {
                // Do something in response to error condition
            }

            do {
                try self.managedContext.save()
            } catch {
                // Do something in response to error condition
            }

        }
    }


    func fetch(entity: String){
        let langfetch = NSFetchRequest(entityName: entity)

        do{
            let results = try managedContext.executeFetchRequest(langfetch)
            languageDB = results as! [NSManagedObject]

        }catch{
            fatalError("bad things happend \(error)")
        }

    }


    func entityIsEmpty(entity: String) -> Bool
    {

        let request = NSFetchRequest(entityName: entity)

        do{
            let results = try managedContext.executeFetchRequest(request)
            languageDB = results as! [NSManagedObject]

        }catch{
            fatalError("Cant handel entity \(error)")
        }

        if languageDB.count != 0
        {
            return true
        }
        else
        {
            return false
        }


    }



}

Solution

  • Presumably this line:

    let fetchRequest = NSFetchRequest(entityName: "MyEntity")
    

    should be using "Language" as the entity name. I suspect that's the source of the error. But I also think your predicate is going to cause problems - it looks like you want only one item saved, so there's no need to filter the results - so no need for a predicate.