Surprising Behavior of Non-optional @NSManaged Properties
A few minutes (or more honestly hours) of debugging later, we notice that the
name
is an empty string only on instances that were deleted from a context and the context was saved. (Deletion of managed objects is unrelated to ARC, so we have objects living in memory even though they are already treated as deleted.)[…]
As pointed out on Reddit replacement of
nil
with an empty string is actually caused by bridging fromNSString
toString
.)[…]
The same silent substitution happens for these types too:
- numeric types use a value equal to
0
Data
uses an emptyData
instance
So this does not seem to be Core Data–specific. However:
This behavior spans relationships too. […] Can you guess what happens? We didn’t set up the
user
relationship, so we should get either anil
or a fatal error, right? Well, we don’t. An empty string is printed in this case too!This is completely counter-intuitive when compared to the normal Swift code:
event.user
isnil
, yetevent.user.name
isn’t.
Here, event.user
was declared as non-optional.