New APIs are hard! Throughout my life as a programmer, I’ve told people that once you master a few languages, learning new ones becomes much easier. But learning to go beyond the language and develop something complex on a new platform is a different beast.
My new challenge is Cocoa. I’m learning Objective-C and the Cocoa (NeXTSTEP) framework to implement a killer solution for graphic designers.
Today, I picked up some chops when it comes to debugging. One of the trickiest things about C is proper memory management, and this carries over to Objective-C. The syntax is simplified, but getting the logic right is just as tough. (Cocoa programmers: obviously I’m talking about traditional retain/release stuff here, not garbage collection).
I spent six hours tracking down a memory management bug. Some object was being over-released, causing my program to crash. I had no idea which object it was, though I had a theory, and I wasted time on it. I didn’t know what to Google for (new platforms are hard), but eventually I landed on it.
The solution? A combination of NSZombieEnabled and MallocStackLogging. NSZombieEnabled proxies release messages. It will never set a retainCount to zero. Instead, it logs a message containing the process ID and memory address of the object being over-released.
Conveniently, MallocStackLogging lets you inspect the stack trace up to the malloc call for a given PID and memory address. Once you find the malloc call, you’ve found your object.
Do I wish I hadn’t spent six hours on this (plus writeup)? No way—it’s struggles like these that help me master a new environment. The best way to learn a new city? Go out and get lost, then find your way back again. The best way to learn a new platform? Hit a wall and learn how to climb over it.