Ios 如何在Swift中更新核心数据中的任何属性?
我读过许多与我的问题有关的问题。我几乎尝试了所有的解决方案,但仍然不起作用 我的问题是我想更新核心数据中名为“Person”的现有对象 这是我的密码: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
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)