How to check if core data is empty

2020-07-13 11:45发布

问题:

How do I check if core data is empty using Swift. I tried this method:

var people = [NSManagedObject]()

if people == nil {

}

but this results in this error:

“binary operator '==' cannot be applied to operands of type [NSManagedObject] and nil”

回答1:

To check if the Core Database is empty you have to make a NSFetchRequest on the entity you want to check, and check if the results of the request are empty.

You can check it with this function:

func entityIsEmpty(entity: String) -> Bool
{

    var appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    var context = NSManagedObjectContext()

    var request = NSFetchRequest(entityName: entity)
    var error = NSErrorPointer()

    var results:NSArray? = self.context.executeFetchRequest(request, error: error)

    if let res = results
    {
        if res.count == 0
        {
            return true
        }
        else
        {
            return false
        }
    }
    else
    {
        println("Error: \(error.debugDescription)")
        return true
    }

}

Or simplier and shorter solution: (using .countForFetchRequest)

func entityIsEmpty(entity: String) -> Bool
{

    var appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    var context = NSManagedObjectContext()

    var request = NSFetchRequest(entityName: entity)
    var error = NSErrorPointer()

    var results:NSArray? = self.context.executeFetchRequest(request, error: error)

    var count = context.countForFetchRequest(request, error: error)

    if error != nil
    {
        println("Error: \(error.debugDescription)")
        return true
    }
    else
    {
        if count == 0
        {
            return true
        }
        else
        {
            return false
        }

    }


}


回答2:

Swift 3 solution:

var isEmpty: Bool {
    do {
        let request = NSFetchRequest(entityName: YOUR_ENTITY)
        let count  = try context.count(for: request)
        return count == 0
    } catch {
        return true
    }
}


回答3:

Based on Dejan Skledar's answer I got rid of some compiler warnings and adopted it to Swift 2.0.

func entityIsEmpty(entity: String) -> Bool
{

    let context = NSManagedObjectContext()
    let request = NSFetchRequest(entityName: entity)
    var results : NSArray?

    do {
        results = try context.executeFetchRequest(request) as! [NSManagedObject]

        return results.count == 0

    } catch let error as NSError {
        // failure
        print("Error: \(error.debugDescription)")
        return true
    }
}

However, I am not sure if the if let res=results clause along with its else clause ist required or not.