以编程方式创建属性 - 核心数据
我有一个简单的 iphone 项目,其中包含一个简单的 xcdatamodel,它有一个实体 大约有 3 个属性..
我想知道是否有一种方法可以以编程方式向实体添加属性.. 即,如果用户按下某种“添加”按钮,则会将一个简单的字符串属性添加到实体中并保存。
如果这是不可能的,有人可以指出我正确的方向吗?
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..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以以编程方式更改实体,但在将托管对象模型分配给托管对象上下文后,您无法更改它,因此它对于任何用户定义的更改都是无用的。无论如何,您都不想以编程方式添加实体,因为这会使您之前创建的持久存储文件变得无用。
如果您想要创建格式更加自由、用户可扩展的数据模型,则必须通过向另一个可以对其他数据建模的实体或实体继承组添加可选关系来使您的实体更加灵活。
例如:假设您有一个联系人列表,并且您想要向每个联系人添加自由格式字段。您可以像这样设置您的实体。
每当用户添加新字段时,您都会创建一个新的 UserDefined 对象并将其添加到 Contact.userDefinedFeilds 关系。您可以根据需要充实它。如果您需要多种类型的用户定义字段,则应按如下方式进行设置:
然后您可以根据需要将 TextField 或 NumberField 对象放入
Contact.userDefinedFields
中。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.
Whenever the user adds a new field, you create a new
UserDefined
object and add it theContact.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: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?