/ objectivec

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!

Save NSSecureCoding-decoding for Dummies
Share this