删除核心数据中的项目

时间:2015-12-05 03:27:03

标签: ios swift core-data

在调用deleteData()方法之前,我已核实我的核心数据中有两个实例。现在我需要删除一个。我提到这个tutorial来删除我的核心数据。

我设法通过此代码将第一个NSManagedObject实例复制到let person = people[0] as! NSManagedObject,但应用已终止此行managedContext.delete(person)

所面临的错误是Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSManagedObjectContext delete:]: unrecognized selector sent to instance 0x7fefe28092e0'

func deleteData() {
    var people = [Particulars]()
    let fetchRequest = NSFetchRequest(entityName: "Particulars")
    let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDel.managedObjectContext

    do {
        people = try managedContext.executeFetchRequest(fetchRequest) as! [Particulars]
        do {
            let person = people[0] as! NSManagedObject
            managedContext.delete(person)
            try managedContext.save()

            } catch let error as NSError {
                print("Could not delete data \(error)")
                }
    } catch let error as NSError
        {
            print("Could not fetch data \(error)")
        }
}

1 个答案:

答案 0 :(得分:0)

正确的通话不是 delete ,而是<{1}}

deleteObject

另请注意,编写NSManagedObjectContext而不是person.first更具可读性,但这当然是品味问题。

我认为people[0]存在问题,因为

  1. 这不安全,如果没有搜索结果会崩溃。使用let person = people[0] as! NSManagedObject ...

  2. if let person = people.firstParticulars的向下转播也没有意义。获取搜索结果后,您已经执行了强制转换。