1

I have read many problems that relate to my problem. I almost try all of the solution but it still not working.

My problem is I want to update an existing object in my core data named "Person"

Here is my code:

func updateDataToCoreData() -> Void {
     var people : [Person]()
    // 1
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext

    // 2
    let fetchRequest = NSFetchRequest(entityName: "Person")

    // 3
    var err : NSError?
    let fetchedResults = managedContext?.executeFetchRequest(fetchRequest, error: &err) as? [Person]

    if let result = fetchedResults {
        people = result

        for index in 0...people.count-1 {
            if people[index].valueForKey("code") as! String == id.text {
                var entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedContext!)
                let batchUpdate = NSBatchUpdateRequest(entity: entity!)
                batchUpdate.resultType = NSBatchUpdateRequestResultType.UpdatedObjectIDsResultType
                batchUpdate.propertiesToUpdate = ["name":"myUpdate"]
                var err : NSError?
                managedContext?.executeRequest(batchUpdate, error: &err)
                if let err = err {
                    println("Error \(err), \(err.userInfo)")
                }
            }
        }
    } else {
        println("cannot fetch data from core data \(err), \(err!.userInfo)")
    }

1 Answer 1

1
(people[index] as! Person).attribute = //set to new value
managedContext.save(nil)
Sign up to request clarification or add additional context in comments.

2 Comments

add this code to which block? And please write the full source code because i'm new with Core Data
anywhere you'd like... depends on when you want the save to happen(i.e. whereEver the value change occurs)...ideally, make appDelegate and managedContext Global vars.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.