如何检查 CoreData 是否为空?

How to check if CoreData is empty?

我正在尝试检查某个实体是否有数据,所以我写了这段代码我不确定我的代码是否如此correct.When我检查我的代码我发现如果有数据我得到的答案是"data exist",但是如果没有数据编译器忽略else语句。我不明白为什么会这样。

   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")
            //}

   } 

编辑后你弄乱了代码。

这会检查获取的数据数组是否为空,如果数组为空returns

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)
    }
}