Swift 3 Core Data Delete Object

后端 未结 8 2162
日久生厌
日久生厌 2020-11-29 02:41

Unfortunately the new Core Data semantics make me crazy. My previous question had a clean code that didn\'t work because of incorrect auto generation of header files. Now I

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 03:30

    Delete core data objects swift 3

    // MARK: Delete Data Records
    
    func deleteRecords() -> Void {
        let moc = getContext()
        let fetchRequest = NSFetchRequest(entityName: "Person")
    
         let result = try? moc.fetch(fetchRequest)
            let resultData = result as! [Person]
    
            for object in resultData {
                moc.delete(object)
            }
    
            do {
                try moc.save()
                print("saved!")
            } catch let error as NSError  {
                print("Could not save \(error), \(error.userInfo)")
            } catch {
    
            }
    
    }
    
    // MARK: Get Context
    
    func getContext () -> NSManagedObjectContext {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        return appDelegate.persistentContainer.viewContext
    } 
    

提交回复
热议问题