Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoreData (IOS) Unique Constraint on Multiple columns?

Is it possible to, in CoreData for an iPhone app, have a Unique Constraint on Multiple columns?

For example:

  • have Event, EventItems, Items entities
  • the EventItems entity has a column ORDER
  • so the ORDER column for an EventItem should be unique for all it's instances relating to the same EVENT

So questions are:

  1. How could I setup this constraint in coredata?
  2. If it's not directly support any suggestions re how to put in place programmatically?
like image 649
Greg Avatar asked Dec 05 '11 01:12

Greg


2 Answers

To do

For any core data constraint that operates on more then a single managed object at once you want to look at implementing:

- (BOOL)validateForDelete:(NSError **)error
- (BOOL)validateForInsert:(NSError **)error
- (BOOL)validateForUpdate:(NSError **)error

(I normally have core data make a .h and .m file for the entity, and then make my own category for things like this so I don't have as much work if I change the entity a little later)

If you have something that only needs to make sure values in a single managed object are correct you can use -validate<Key>:error:

To do what you are looking for I would make EventItems' validateForInsert/validateForUpdate call a common method (maybe validateUniqueOrder). In that method I would use the relationship from EventItems to Event, and then fetch all the EventItems relating to the Event, and then check for uniqueness. I have fairly small sets of relations, so I didn't bother with anything fancy, but if you have a lot of event items associated with given events you might look into NSFetchRequests' setPropertiesToFetch method. Or maybe you can come up with a query that can directly search for duplicated values (I never could, so if you do, reply here to enlighten me).

like image 59
Stripes Avatar answered Oct 24 '22 03:10

Stripes


How could I setup this constraint in coredata?

You control what goes into the data store, so you can impose any constraints you like, no matter how complex. But Core Data is not a database, and it doesn't implement the kinds of automatic constraints that you typically find in a RDBMS.

If it's not directly support any suggestions re how to put in place programmatically?

I'd do a check at the point in your code where you create or modify the affected object. In your case, you could create a custom setter for EventItem's 'order' property that compares the proposed 'order' to that of all the other EventItems related to the same event. Or, you might put the check in Event, and use an appropriate accessor to check any new EventItems as they're added.

like image 3
Caleb Avatar answered Oct 24 '22 04:10

Caleb