Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何在Swift中更新核心数据中的任何属性?_Ios_Swift_Core Data - Fatal编程技术网

Ios 如何在Swift中更新核心数据中的任何属性?

Ios 如何在Swift中更新核心数据中的任何属性?,ios,swift,core-data,Ios,Swift,Core Data,我读过许多与我的问题有关的问题。我几乎尝试了所有的解决方案,但仍然不起作用 我的问题是我想更新核心数据中名为“Person”的现有对象 这是我的密码: func updateDataToCoreData() -> Void { var people : [Person]() // 1 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let manage

我读过许多与我的问题有关的问题。我几乎尝试了所有的解决方案,但仍然不起作用

我的问题是我想更新核心数据中名为“Person”的现有对象

这是我的密码:

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

将此代码添加到哪个块?请写完整的源代码,因为我是一个新的核心数据的任何地方,你想。。。取决于您希望保存的时间(即值更改发生的位置)…理想情况下,使用
appDelegate
managedContext
全局变量。
(people[index] as! Person).attribute = //set to new value
managedContext.save(nil)