Programmatically create attribute - Core Data

北慕城南 提交于 2019-12-19 04:50:21

问题


i have a simple iphone project which contains a simple xcdatamodel that has a single entity with roughly 3 attributes..

i want to know if there is a way to programmatically add an attribute to an entity.. i.e. if the user presses an "add" button of some kind, a simple string attribute is added to the entity and saved..

If this is not possible could someone point me in the right direction..


回答1:


You can programmatically alter entities but you can't alter a managed object model after it has been assigned to a managed object context so that makes it useless for any user defined alterations. In any case, you wouldn't want to add entities programmatically because that would make your previously created persistent store file useless.

If you want to create a more free-form , user extensible data model, you have to back out and make your entities more flexible by adding an optional relationship to another entity or entity inheritance group that can model additional data.

For example: Suppose you have a contact list and you want to add free form fields to each contact. You would set up your entities like this.

Contact{
    name:string
    phone:string
    userDefinedFields<-->>UserDefined.contact
}

UserDefined{
    name:string
    contact<<-->Contact.userDefinedFields
}

Whenever the user adds a new field, you create a new UserDefined object and add it the Contact.userDefinedFeilds relationship. You can flesh that out as needed. If you need more than one type of user defined field you should set it up like this:

Contact{
    name:string
    phone:string
    userDefinedFields<-->>UserDefined.contact
}

UserDefined{
    name:string
    contact<<-->Contact.userDefinedFields
}

TextField:UserDefined{
    text:string
}

NumberField:UserDefined{
    numValue:Number
}

You can then drop in a TextField or NumberField object into the Contact.userDefinedFields as needed.




回答2:


i am not so sure if you can add an attribute with code, but maybe you can consider using one to many relationship?



来源:https://stackoverflow.com/questions/5536502/programmatically-create-attribute-core-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!