CoreData - can't set empty string as default v

2020-05-29 13:20发布

I have an entity in my datamodel with a string attribute that is currently optional, and I'd like to convert this to a required attribute with a default value of the empty string.

As others have discovered, leaving the default value blank in the Xcode CoreData data modeller results in validation errors (since the designer interprets this as NULL), but trying '', "", or @"" as the default value results in those literal characters being interpreted as the default, rather than the empty zero-length string, as desired.

I did find this thread on Google, however, apart from the solution being really ugly (model definition split between the .xcdatamodel and objc source), it also doesn't work for lightweight migrations because those migrations are done solely based on the .xcdatamodel files and the objc logic from your entity implementations isn't loaded.

Is there any way to achieve this in the data model designer?

8条回答
女痞
2楼-- · 2020-05-29 13:59

Maybe I'm late with this answer, but I was Googling and found this forum.

The solution is very simple:

  1. When you click on the xcdatamodelId (On the left screen)
  2. Change the Entity View to Graph
  3. Double Click on any Attribute you want and the menu will appear on the right.

All changes are easy.

Part 2

For Part 2

Part 3

For Part 3

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-05-29 14:04

Whip out your favorite XML editor (I just used Emacs) and dive down to the contents file inside the .xcdatamodel bundle inside the .xcdatamodeld bundle. Then just add a defaultValueString="" XML attribute to the <attribute>...</attribute> element inside the <entity>...</entity> brackets. Here's an example:

<attribute name="email" attributeType="String" defaultValueString="" syncable="YES"/>

I can't speak to whether this survives migration since I haven't had to do that yet.

查看更多
登录 后发表回答