Writing Better Objective-C: Warnings, Analyzer and Namespaces
Three quick tips to improve your Objective-C code.
First, make sure your code compiles without warnings. The compiler should be your friend. If it doesn’t like something, it usually has a point and the code in question is awkward or downright wrong. Some warnings are harmless, but you can’t leave them in the code anyway, since they would make it harder to notice the important ones. Also, when you later pass the code to somebody else or return to it a month later, would you know which warnings were OK? If there’s no reasonable way to rewrite the code without triggering a warning, use a compiler pragma to silence it. And finally, there’s a compiler switch for turning all warnings into errors. Consider using it, keeps you honest. (Some languages like Go even went as far as to treat all warnings as hard errors by design.)
The same reasoning applies to the static code analyzer (Product → Analyze in Xcode). You even have the option to run the analyzer as a part of the build, which might be a good idea, at least for some build configurations.
Both previous tips should be a natural thing for any professional programmer. The third one is not a hard requirement, but a reasonable idea anyway – it’s about prefixing your symbol names with a personal name prefix. The problem is that Objective-C lacks namespaces, a tool to distinguish between two symbols with the same name coming from two different packages. If you have two different
Vector classes, in Perl you could have
Other::Vector, in Java you have the URL prefix to tell them apart. In Objective-C you just have a class name conflict. That’s why most symbols have the strange prefixes in their names, such as
UIView. It’s poor man’s namespaces.
It’s a good idea to join the game and pick a reasonable symbol prefix, too. It makes the (small) chance of a name conflict smaller and the code more consistent. Also, you get a slight bonus in the auto-completion, since typing your class prefix quickly narrows down the suggest options.