Kotan Code 枯淡コード

In search of simple, elegant code

Menu Close

Google Protocol Buffers on iOS and Mac – Redux

In a previous blog post, I talked about how I used the C++ stock Google Protocol Buffers generated code and the native C++ library in my iOS application. It involved some trickery of creating a wrapper Objective-C++ class to keep the C++ from bleeding into my Cocoa project, I had to link a static library, and it actually bloated my application quite a bit.

Since then, I have found a great native Objective-C protobuf implementation that not only plugs into the regular protoc compiler, but it generates ARC-friendly code. Check out this library on Github for the Objective-C protobuf code.

Now, rather than fussing with creating a C++ object (which requires me to manually malloc and free!), I can just create a new protobuf object that feels natural and native to my iOS and Mac code:

ZombieSighting *sighting =
        [[[[[[[ZombieSighting builder] setDescription:@"This is a zombie"]
                setLatitude:21.007]
                setLongitude:18.214]
                setZombieType:ZombieTypeFast]
                setName:@"Lord Kevin of the Undead"] build];

With this implementation of protobufs, I can just do [sighting data] to get the NSData for the object, and I can de-serialize a protobuf object that I plucked off the wire far more easily than before:

DirectMessage *dm = [DirectMessage parseFromData:data];

See how much easier and cleaner everything is? The moral of the story here is good enough isn’t good enough. Just because you find one solution doesn’t mean it’s the best one. I am constantly in search of simpler, easier, more elegant ways of doing things and I think I’ve finally found a decent way of dealing with protobufs in Objective-C.