So, last time I wrote about what you need to get started with iPhone development. I thought now would be a good time to talk about stuff I encountered along the way, which I guess almost anyone developing for iPhone would encounter eventually.
This time, let me focus on memory management. Objective-C uses reference counting for its memory management, and the version running on the iPhone does not have garbage collection (yes, this is so 90s..). Anyway, this forces the developer to actually think about what is being allocated, when and where. Apple has a guide about Objective-C memory management in its developers’ resources, begin by reading it.. Assuming it’s clear enough, the next thing to do is to actually check your program for leaks (if you’re a beginner, there are leaks – trust me..). Luckily, Apple provides a tool along with its SDK called Leaks (here’s one place where they didn’t think they need to be original..), which tracks your program in runtime (on the actual device, actually, which is pretty cool and also recommended, as the device behaves differently than the simulator in some aspects, and memory is one of those..) and marks places with leaks. The tool is very nice, but in my opinion not the friendliest tool for beginners. One downside is – it can only detect flows you actually went through (obviously), and it’s sometimes hard to determine what’s the actual source of the leak. Still, if there’s a leak during runtime and yo u passed through the leaking flow, this is your best chance to catch it.
One downside I didn’t mention about the Leaks tool and which is not that obvious, is that even when you find a leak, it’s not always obvious why are things behaving the way they are. It so happens that I found a great tool which does static analysis for Objective-C code, and the best thing about it is that when it finds bugs (memory leaks are bugs, duh..), it also explains why is that a bug. The tool is called Clang Static Analyzer and it’s pretty straight forward to use – you download it, extract it, and then use two simple commands:
(This should be executed in your program’s home directory).
Then, once this is done, a report will be generated and the last line in the verbose output of the build will have the report name, then simply execute>
/path/to/clang/installation/scan-view <report name>
Which will open a browser window with your report, links to the source files and cool embedded explanations. Once you do the fixes, execute the scan again and check there are no more errors.. note that the default behavior if there are no errors is not to generate a report at all..
So, that’s it for now. More on the fun in iPhone development next time..