swiftcore-datanspersistentdocument

Document based core data app - add and remove additional attributes


I have a document based core data app with entity "Languages". This entity has two permanent attributes "key" and "comments". Is it possible programmatically add and remove additional attributes during runtime ("language_1", "language_2", etc.) ?

My goal is to avoid creating table with let say 50 attributes when user needs only few (I don't know upfront how many attributes will be necessary).

Or maybe I should choose other solution ? :)

EDIT

Case explanation: When user creates new document, table "Languages" has only 2 attributes "key" and "comments". During working with the document user can any time add or remove language(s) - I mean attributes (columns) not rows in the table.

My goal is to have dynamic entity like below.

database explanation

data structure


Solution

  • Yes, it's possible. But it's probably not what you want. You'd have to recreate the amended Managed Object Model, for each document, at runtime whenever the document is opened.

    After seeing your sketch, I suggest a slightly different model. By the way, best style is to use singular nouns for Entities ("Section", not "Sections), plural nouns for to-many Relationships ("sections", not "relSection"), and omit the entity name in its attributes ("comment", not "sectionComment").

    Use one Entity for your permanent attributes. Call it "Word". Word has attributes "comments" and "key", and to-many relationships "translations" and "sections". On the other end of the "translations" relationship is a Translation entity, which has attributes "text" and also perhaps the name of the language (either as a string or as another relationship).

    Something like this:

    data model

    For your first example, you'd have one instance of Word, 3 instances of Translation (.text = Home, Zuhause, and Casa), and 3 instances of Language (.name = English, German, Spanish). When you add the second line, you'll get 1 more instance of Word, 3 more instances of Translation, but 0 more Languages. Add the new Translation instances to the existing Language's "translations" relationship instead.