开发者

Programmatically create attribute - Core Data

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..


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜