Dave G Dave G - 1 month ago 4
Swift Question

CoreData - Safely Check Value of CoreData Object

The way I currently have my code arranged, the following line will run for various managed-object-contexts. Some of the fetched entities will have "complededDate" and others will not have a "completedDate" attribute.

let task = retrieved_MgObjCntxt[(indexPath as NSIndexPath).row]
if let itemFinDate = task.value(forKey: "completedDate") {
...


I thought by using if-let, that if this failed then it'd be okay... but I'm getting an "lldb" crash. I've been playing with trying to solve it using do/catch and throw but I'm not super familiar with how those work.

Is there a way to safely check so that if "completedDate" doesn't exist, it just skips the code within the if-closure??

Answer
let task = retrieved_MgObjCntxt[(indexPath as NSIndexPath).row]
if task.entity.propertiesByName.keys.contains("completeDate") {
    ...
}
Comments