Reputation: 17
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")
//}
}
Upvotes: 0
Views: 1254
Reputation: 285064
After the edit you messed up the code.
This checks if the fetched data array is empty and return
s 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)
}
}
Upvotes: 1