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 } } }
source share