DEV Community

Nathan Mattes
Nathan Mattes

Posted on β€’ Originally published at zeitschlag.net on

1

Save NSSecureCoding-decoding for Dummies

After my last wrong assumption, that I don't need to look up easy things, I stumbled upon this assumption again. This week, I failed to implement NSSecureCoding the right way. In the end, I learned some things.

I wanted to persist some data using NSSecureCoding, NSKeyedArchiver and NSKeyedUnarchiver. I haven't used NSSecureCoding before, but hey, how difficult could it be?

  1. Just implement -encodeWithCoder:, -initWithCoder: and supportSecureCoding.
  2. Encode with NSKeyedArchiver, decode with NSKeyedUnarchiver.
  3. There's not 3

These were my assumption, but it didn't work β€” what a freaking surprise! πŸŽ‰. If I would read the documentation beforehand, I could have saved several hours.

Both Apple's documentation β€” and NSHipster state:

Specifically, classes that override -initWithCoder and conform to NSSecureCoding should use -decodeObjectOfClass:forKey: rather than decodeObjectForKey:

Source: NSHipster

An object that does override initWithCoder: must decode any enclosed objects using the decodeObjectOfClass:forKey: method.

Source: Apple's Documentation on NSSecureCoding

My mistake was to use just -decodeObjectForKey: for decoding. For an NSString, everything went fine. I found my mistake, when I was wondering, why I can't decode my encoded NSData. There were some mysterious error messages in the debugger, but I still doubted my code: This was so easy, it wasn't even worth to stack-overflow this issue!

After a while, I read the documentation by accident. I saw my misconception then, fixed the issue, and suddenly, everything worked as intended. In the end, I felt pretty stupid, although I learned some things:

  • How decoding with NSSecureCoding works
  • Read the freaking documentation, folks! NSHipster might be worth reading, too.
  • Don't ignore the little "don't assume, prove!"-post-it-sticker next to my screen.

Thanks for reading!

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay