Search code examples
swiftcore-dataswift4xcdatamodel

How to check if CoreData is empty?


I am trying to check if certain entity has data, so I wrote this code I am not sure if my code correct.When I check my code I found that if there is a data I got the answer that "data exist", but if there is no data compiler ignore else statement. I cannot understand why this happen.

   func entityIsEmpty()
   {
     let context = objAppDelegate.persistentContainer.viewContext
     let fetchRequest = NSFetchRequest<NSFetchRequestResult>.init(entityName: "myEntity")

     //do{
     //result = try context.fetch(fetchRequest) as! [NSManagedObject]
     result = fetchRequest as! [NSManagedObject] //ERROR
     for data in result{

     var obj = userNSObj()
     obj.myObject = data.value(forKey: "myAttribute") as! String


     myArray.append(obj)
        if myArray != nil{
            print("data exist")
        }else{
            print("data not exist")
        }
                        }

             //}catch{
             //print("Failed")
            //}

   } 

Solution

  • After the edit you messed up the code.

    This checks if the fetched data array is empty and returns if the array is empty

    func entityIsEmpty()
    {
        let context = objAppDelegate.persistentContainer.viewContext
        let fetchRequest = NSFetchRequest<myEntity>(entityName: "myEntity")
    
        do {
            let result = try context.fetch(fetchRequest)
            if result.isEmpty {
                print("data not exist")
                return
            } else {
                print("data exist")
            }
    
            for data in result {
                var obj = userNSObj()
                obj.myObject = data.myAttribute
                myArray.append(obj)
            }
    
        } catch {
            print(error)
        }
    }