且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

CoreData - 不能将空字符串设置为属性的默认值

更新时间:2022-10-15 16:37:18

这是一个非常有趣的问题.经过一些测试,我认为这是不可能的,因为数据模型中的文本字段的配置方式.

This is a very interesting question. After some testing I don't think this is possible because of the way the text field in the data model is configured.

原则上,您可以使用 u2205 的 unicode 空集字符来表示默认的空字符串,但文本字段似乎不接受任何转义,因此它会将任何尝试转义unicode 字符代码到代码字符本身的文字字符串,例如输入 'u2205' 以文字文本 'u2205' 结束.

In principle, you could use the unicode empty-set character of u2205 to represent a default empty string but the text field does not seem to accept any escapes so it converts any attempt to escape a unicode character code to the literal string of the code characters themselves e.g. entering 'u2205' ends up as the literal text 'u2205'.

理论上,您可以编写一个实用程序来读取以图形方式生成的托管对象模型文件,然后以编程方式将属性默认值设置为空字符串,然后将文件保存回磁盘.我说理论上"是因为没有记录的方法可以从代码中保存托管对象模型文件.您可以读取一个并在内存中对其进行修改,但不能保留更改.

In theory you could write a utility app to read in the graphically generated managed object model file and then programmatically set the attribute default to equal an empty string and then save the file back to disk. I say "in theory" because there is no documented way to way to save a managed object model file from code. You can read one and modify it in memory but not persist the changes.

我认为有点疏忽.

我认为您别无选择,只能在模型首次加载时实用地设置默认空字符串.这很简单,但很丑陋,你必须记住你做过(特别是如果你迁移版本),但我认为现在这是唯一的选择.

I don't think you have any choice but to set the default empty string pragmatically when the model first loads. That is simple to do but it's ugly and you'll have to remember you did (especially if you migrate versions) but I think right now that is the only choice.