Reputation: 82
I have to create and remove attributes based on an api response in Objective C. For example, Now my api response contains fields "facebook", "whatsapp" and "viber". But in future the reponse can add "youtube". Based on this response, I have to remove all the attributes and values of an entity "Social", and create Four attributes now and set values. How to do that programmatically? Because the default *.xcdatamodeld file cant help me here, right? Note: My project is in objective C.
Upvotes: 0
Views: 693
Reputation: 70966
The data model is mutable when the app starts-- you can completely build the model in code, and not use the model editor, for example. But as soon as you load a persistent store file, you must treat the model as fixed. Any changes after loading a persistent store will cause crashes. That means any changes would have to happen before calling either loadPersistentStores(completionHandler:)
or addPersistentStore(with:completionHandler:)
.
Alexander's suggestion of optional attributes is a good one. If you need the model to be more dynamic, you would need to create a new related entity which would store the service name plus whatever information you need to save about the service. If you did this, your Social
entity would have a to-many relationship to a new entity called something like Service
. Service
would have a string property called name
that would have values like twitter, facebook, youtube, etc. It would also have whatever other attributes you need to save about the service.
Upvotes: 2
Reputation: 2513
You can create all 4 fields in advance and just make them optional and fill them depending on the server response. But you cannot add new attributes in runtime. Your *.xcdatamodeld
file compiles into *.momd
and it contains all the data to create tables in the DB since Core Data by default works with SQLite under the hood and it's a relational database management system.
To make attributes optional you should check that.
And then newly created objects contain nil
as default values of object properties. So, in your case your "youtube" property of Social
object will be just nil
.
Upvotes: 0