Monday, September 25, 2017 [Tweets] [Favorites]

Surprising Behavior of Non-optional @NSManaged Properties

Arek Holko:

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 from NSString to String.)

[…]

The same silent substitution happens for these types too:

  • numeric types use a value equal to 0
  • Data uses an empty Data 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 a nil 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 is nil, yet event.user.name isn’t.

Here, event.user was declared as non-optional.

Comments

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment