Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value to core data attributes (column) for iOS programmatically

Current Approach

  • I set the default value of the attribute directly to the data model file using the inspector.

Problem

  • I have enum for the values a particular attribute can take.
  • I am worried maintaining them at a later stage might be difficult.
  • Suppose if I decide to change the enum values, then I would have to manually go the inspector and change it.
  • Since I have quite a number of attributes based on enum values, it becomes difficult.

Question

  • How can I add default values to core data attributes programmatically ?
  • Is there any alternative to do this, so that maintenance would be easier ?
like image 588
user1046037 Avatar asked Jan 21 '26 20:01

user1046037


1 Answers

Everything you can do graphically in the Core Data model editor you can do using the classes Core Data provides for creating/introspecting a managed object model. For this use case, you can use NSEntityDescription to look up an entity, its properties or propertiesByName accessors to find the NSAttributeDescription for the attribute you're interested, and setDefaultValue: to do the same thing the Core Data model editor does.

You might find this the most appropriate way to do what you're looking for. Or, as @DimitryShevchenko notes, you can initialize values in your NSManagedObject subclass' awakeFromInsert method -- which way you choose might depend on your workflow or other requirements of your application.

like image 160
rickster Avatar answered Jan 24 '26 10:01

rickster