Search code examples
swiftcore-datasetvalue

Where to place update core data function (swift)


I've done some research on how update core data and I've found the setValue() function.

I'm now struggling on where to call this function. Obviously I would call it when the data is changed:

if (textField.text != detail!.valueForKey("name")!.description {
        detail?.setValue(textField.text, forKey: "name")
    }

Where would I place this? I doubt that it belongs in viewDidLoad and configureView. This is for my detailViewController file.

textField is:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TextFieldTableViewCell
    let textField: UITextField = cell.textField
    let detail = self.detailItem
    
    textField.text = detail!.valueForKey("name")!.description
    return cell
}

Solved

textFieldDidEndEditing() solved the problem of checking if the value is changed and saves it.

Passing a textField that is a subclass of UITableViewCell is solved here: How to call textField that is a inside of UITableViewCell (swift)


Solution

  • class ViewController: UIViewController,UITextFieldDelegate {
    
        @IBOutlet weak var txtName: UITextField!
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
            txtName.delegate = self
        }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
            print("Tells the delegate that editing ends for specific textfield")
    
    if (textField.text != detail!.valueForKey("name")!.description {
            detail?.setValue(textField.text, forKey: "name")
        }
        }
    }
    

    Hope This will be helpful..