How to check if kernel data was empty

How to check if kernel data was empty using swift. I tried this method:

var people = [NSManagedObject]() if people == nil { } 

but this leads to an error

"the binary operator '==' cannot be applied to operands like [NSManagedObject] and nil"

+5
source share
3 answers

To check if the base database is empty, you should do NSFetchRequest on the entity you want to check and check if the query results are empty.

You can check this 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 a simpler 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 } } } 
+4
source

Swift 3 solution:

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

Based on Dejan Skledar's answer, I got rid of some compiler warnings and accepted it in 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'm not sure if let res=results clause is required along with its else clause or not.

+4
source

All Articles