Ios 更新CoreData对象

Ios 更新CoreData对象,ios,uitableview,swift,core-data,Ios,Uitableview,Swift,Core Data,我想更新CoreData对象。 Backgrund:我制作了一个包含UITableView的应用程序。UITableViewCell的文本标签中有一个名称。此单元格的detailTextLabel中有一个可以更改/更新的日期。现在我想更改这个日期 我编写了以下代码: var people = [NSManagedObject]() func saveDate(date: NSDate) { //1 let appDelegate = UIApplication.

我想更新CoreData对象。 Backgrund:我制作了一个包含UITableView的应用程序。UITableViewCell的文本标签中有一个名称。此单元格的detailTextLabel中有一个可以更改/更新的日期。现在我想更改这个日期

我编写了以下代码:

 var people = [NSManagedObject]()


 func saveDate(date: NSDate) {

      //1
      let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
      let managedContext = appDelegate.managedObjectContext!

      //2
      let entity =  NSEntityDescription.entityForName("Person", inManagedObjectContext:managedContext)
      let person = people[dateIndexPath.row]

      //3
      person.setValue(date, forKey: "datum")

      //4
      var error: NSError?
      if !managedContext.save(&error) {
          println("Could not save \(error), \(error?.userInfo)")
      }

      //5
      people.append(person)
      tableView.reloadData()
 }
现在,如果我运行以下代码: 已成功更新日期,但已更新日期的单元格显示2次。例如,如果我添加了3个单元格并更改了第3个单元格中的日期,我现在会显示4个单元格,其中2个单元格的内容相同/重复


有人知道如何解决这个问题吗?

您每次都在向数组中添加一个额外的对象。更新的
人员
已在数组中,并将在重新加载表格数据时显示新信息。要解决此问题,只需取出以下行:

people.append(person)

您需要将某种唯一标识符属性与
Person
类相关联。这允许以后使用它的标识符检索相同的对象。我建议使用
UUID
字符串值,称为
personID
标识符,
或类似的东西

您可以在
Person
类上重写
awakeFromInsert
方法,如下所示:

// This is called when a new Person is inserted into a context
override func awakeFromInsert()
{
    super.awakeFromInsert()

    // Automatically assign a randomly-generated UUID
    self.identifier = NSUUID().UUIDString
}
当您想要编辑现有人员时,您需要通过
UUID
检索该人员。我建议这样的类函数(在
Person
类中):

通过这种方式,您可以使用以下功能:

let identifier = ...
let context = ...

var person = Person.personWithIdentifier(identifier, inContext: context)

if let person = person
{
  // Edit the person
  person.value = // change the values as you need
}
else
{
   // Person does not exist!
   person = // possibly create a person?
}  

谢谢你的回答!现在复制的细胞不再出现了。但是,如果我添加了3个单元格并更改了第3个单元格的日期,则第1个单元格的日期也会更新为新日期,而新日期只应在第3个单元格中设置。如果我重新启动应用程序,所有都是正确的(只有第三个单元格被更新)。你知道为什么吗?日期从哪里来?我需要看更多你的代码。
let identifier = ...
let context = ...

var person = Person.personWithIdentifier(identifier, inContext: context)

if let person = person
{
  // Edit the person
  person.value = // change the values as you need
}
else
{
   // Person does not exist!
   person = // possibly create a person?
}