dyatesupnorth
dyatesupnorth

Reputation: 830

How to check a related entity exists in Core Data?

So, I'm needing to check wether an entity exists, and if one doesn't create it.

Currently, my Core Data db is populated by JSON, I get a Work object which may or may not contain a Survey object. If it contains a survey I populate the survey fields and then attach it to my Work like so:

let newWorkObj = NSEntityDescription.insertNewObjectForEntityForName("Work", inManagedObjectContext: moc) as! Work
let newSurveyObj = NSEntityDescription.insertNewObjectForEntityForName("Survey", inManagedObjectContext: moc) as! Survey

//newSurvey.field = obj["field"].string etc...

newWorkObj.survey = newSurvey

Then, later , I'm needing to check if a work.survey exists...how do I do it?

I already tried adding a isPresent field inside the entity, then realised that the application will crash before it even gets to that check (an entity has to exist before anything can be checked inside it...)

Hopefully I will be able to do something like

 if work.survey.EXISTS  {

     //sit back and chill

 }else{

     //make a new entity

 }

Everything I have seen assumes I am searching for multiple objects and likes to use NSPredicate, surely there's a simpler way of checking wether an entity exists?

Upvotes: 1

Views: 141

Answers (1)

deleterOfWorlds
deleterOfWorlds

Reputation: 552

Assuming your Work entity has a to-one relationship with your Survey entity, and that you defined it something like:

@NSManaged var survey: Survey?

in your Work class, then you should be able to check if it's set by writing:

if work.survey != nil {
    // sit back and chill
} else {
   // make a new entity
}

Upvotes: 1

Related Questions