Dave
Dave

Reputation: 12216

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??

Upvotes: 0

Views: 31

Answers (2)

Lukas
Lukas

Reputation: 3433

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

Upvotes: 1

Olivier Wilkinson
Olivier Wilkinson

Reputation: 2856

You can find all the keys for you objects entity type by using:

managedObject.entity.attributesByName

And then see if that dictionary's keys contains "completedDate"

Upvotes: 0

Related Questions