Faking a dynamic schema in Core Data?

1.2k views Asked by At

From reading the Apple Docs on Core Data, I've learned that you should not use Core Data when you need a dynamic schema. If I wanted to provide the user the ability to create their own properties, in a core data model would it work if I created some "dummy" attributes like "custom decimal 1", "custom decimal 2", "custom text 1", "custom text 2" etc that the user could name and use for their own purposes?

Obviously this won't work for relationships, but for simple properties it seems like a reasonable workaround. Will creating a bunch of dummy attributes on my entities that go unused by most users noticeably decrease performance for them? Have any of you tried something like this? Thanks!

3

There are 3 answers

1
Matthew Flaschen On BEST ANSWER

First, see the Core Data docs on relationships. Using your example, consider something like:

  1. A CarAttributeType entity, with a name such as "weight in pounds"
  2. A CarAttribute entity with a value such as 2765.
  3. A Car entity, with the required values you mentioned (such as "color", "make", etc.)

Then, have a many-to-one relationship between CarAttribute and CarAttributeType (many CarAttributes can have the same type), a one-to-many relationship between Car and CarAttribute (each car can have many attributes). This solution is a bit more complicated to setup than the hard-coded NULL fields. However, it avoids repeating groups and is hopefully more maintainable.

EDIT: Yes, I missed that. I think you would want a StringCarAttribute, StringCarAttributeType, FloatCarAttribute, FloatCarAttributeType, etc. Then, have a many-to-one between StringCarAttribute and StringCarAttributeType, etc. Car will have one-to-manys with both StringCarAttribute and FloatCarAttribute. The reason for multiple type entities is so you don't have a StringCarAttribute and FloatCarAttribute, both declaring themselves to be using a single weight attribute type.

Having one CarAttribute with all the types goes against 1NF #4.

1
Jared Pochtar On

It would work, it would just be awful. Think using a flat table in a database, because thats exactly what you'd be doing. Instead try creating a schema that can describe a schema in a way that your application can understand. There would still be considerable code involved however, although if done correctly you could mimic as much as a SQL database. Of course, core data is built on top of SQL (or other storage types but thats not my point), but basically you'd be creating a layer to mimic something two layers down which would just be silly.

0
Mike Abdullah On

One option is KSExtensibleManagedObject. Shove the dynamic schema bit in the extensible properties.