Objective-C is a big pain in the ass when it comes to serialize instances
of your custom classes inheriting from NSObject
. If you Google how to
you serialize your custom objects into JSON, you will get tens of results
saying “implement NSCoding
” protocol. Biggest take of this post will be:
You don’t need to implement NSCoding
. Here’s why:
First of all, take a look at Sam’s article on
how to implement NSCoding
protocol. First thing you see is, you have
to write encode/decode statements for every single member you have in your
custom class. As a Java/C#/Go/Python developer (or whatever) first thing you
think is this is too much boilerplate for a simple object model.
While digging more on this, I found a library probably nobody uses.
It has only a few stars on GitHub, but guess what, it does the trick. Check
out KVCObjectSerializer
on GitHub. I’m telling you how to use
it in two steps:
First, you need to derive your class from KVCBaseObject
instead of NSObject
and then:
NSString *jsonString = [customObj objectToJson]; // or:
NSDictionary *dict = [customObj objectToDictionary];
Tada! That easy. It also handles serialization of NSArray
and NSDictionary
members (which already implement NSCoding
by default) in your custom class.
It also supports recursion on members of other custom classes.
A better solution?
Check out GitHub’s Mantle. It gives you more control e.g. you can change name mappings of members, provide custom serializers for each member. It also has JSON serialization capabilities and much more advanced in so many ways.
If you go with Mantle, you inherit your class from MTLModel
which does
conform to NSCoding
automatically so you can persist your objects into files
easily as well. It also has CocoaPods integration, which is cool.
Why use this?
Conforming to NSCoding
is prone to errors, there is a chance you can always
forget to add new fields in your custom class. This is also not practical at
all, on an average project you would have a few entity classes and you got to
implement NSCoding
to save them on NSUserDefaults
or write to a file etc.
This library fits very well if you are going to consume REST API responses in your app. It gives you almost no control, but in turn it is plug-and-play.
Check out Mantle’s readme on why not use NSCoding
and
why not use Core Data.
When not to use this?
If you have no performance concerns (I can’t think of any) and if your custom
classes do not have complex-to-serialize members (e.g. buffers, NSData
or
non-serializable stuff) you should go for KVCObjectSerializer
.
Leave your thoughts