swift 删除核心数据元素

hwamh0ep  于 2023-08-02  发布在  Swift
关注(0)|答案(4)|浏览(113)

我正试图实现一个功能,以删除闪存卡在一组自定义闪存卡,但我有麻烦的CoreData方面的。这应该做的是循环通过保存的卡,如果它与要删除的卡匹配,那么我们将从当前卡组中删除它并保存上下文,有人知道出了什么问题吗?使用断点,我可以确认if语句确实执行了,因此它具有内部逻辑

do {
    self.fetchedCards = try context.fetch(Cards.fetchRequest())
    for card in self.fetchedCards {
        if(self.termLabel.text == card.term){
        self.managedDeck?.removeFromCards(card)
        ad.saveContext()
        break
        }
     }
 } catch {
   }

字符串

eeq64g8w

eeq64g8w1#

请使用此功能删除核心数据中的所有数据

func deleteAllData(entity: String) {
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext
    let fetchRequest = NSFetchRequest(entityName: entity)
    fetchRequest.returnsObjectsAsFaults = false

    do {
        let results = try managedContext.executeFetchRequest(fetchRequest)
        for managedObject in results
        {
            let managedObjectData:NSManagedObject = managedObject as! NSManagedObject
            managedContext.deleteObject(managedObjectData)
            print("Deleted")
        }
    } catch let error as NSError {
        print(error)
    }
}

字符串

w6lpcovy

w6lpcovy2#

删除所有数据可以使用此函数

func deleteAllData(entity: String) {

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext
    let fetchRequest = NSFetchRequest(entityName: entity)
    fetchRequest.returnsObjectsAsFaults = false

    do
    {
        let results = try managedContext.executeFetchRequest(fetchRequest)
        for managedObject in results
        {
            let managedObjectData:NSManagedObject = managedObject as! NSManagedObject
            managedContext.deleteObject(managedObjectData)
            print("Deleted")
        }

    } catch let error as NSError {
        print(error)
    }
}

字符串
用途:

deleteAllData(entity: "your Entity name")

ipakzgxi

ipakzgxi3#

var cards = try! context.fetch(Cards.fetchRequest())

for card in cards {
    if (self.termLabel.text == card.term) {
        context.delete(card)
    }
}
try! context.save()

字符串

iaqfqrcu

iaqfqrcu4#

if语句中,我需要context.delete(card)而不是self.managedDeck?.removeFromCards(card)

相关问题