iOS: Delete ALL Core Data Swift

前端 未结 23 688
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 11:20

I am a little confused as to how to delete all core data in swift. I have created a button with an IBAction linked. On the click of the button I have the follow

23条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 12:01

    static func fetch(entity: T.Type, withPredicate predicate: NSPredicate? = nil) -> Array? where T : NSManagedObject {
        let request: NSFetchRequest = NSFetchRequest(entityName: String(describing: T.self))
        request.predicate = predicate
        do {
            return try context.fetch(request)
        }catch{
            print(error.localizedDescription)
        }
        return nil
    }
    
     static func delete(_ object: T) where T : NSManagedObject {
        context.delete(object)
        saveContext()
    }
    
    static func reset(entity: T.Type) where T : NSManagedObject {
        fetch(entity: entity.self)?.forEach{
            delete($0)
        }
    
    }
    

提交回复
热议问题