Using Subscripting With Xcode 4.4 and iOS 4.3+
Now that Xcode 4.4 has finally reached Golden Master and you can submit apps, here’s a trick to use subscripting right now. Yes, Apple will introduce this feature in a future version of OS X and iOS, but why wait? Here’s the snippet from PSPDFKit, my iOS PDF framework, to make it work:
It’s a bit crude, and Xcode won’t show any warnings if you’re doing subscripting on any object now, but you know what you’re doing, right? Furthermore this is only temporary, to make it compile with Xcode 4.4. In Xcode 4.5, this snippet won’t do anything and isn’t needed anymore, since the new SDK already has those methods defined on the classes you care about. Just make sure this is in your global header file (e.g. precompiled headers).
Note that unlike literals, which are really just syntactical sugar and already work great in Xcode 4.4+ (LLVM 4.0+), subscripting actually calls into new methods. So how does this “magically defining headers” actually work?
Thanks to Mike Ash and Cédric Luthi, here’s the answer:
The subscripting compatibility shim is actually part of ARCLite. The ARCLite load function takes care of dynamically adding the four subscript methods with class_addMethod. The implementations of these methods simply call the equivalent non-subscript methods.
If you, for any reason, are not on ARC yet, you really want to force the compiler to link with libarclite using the -fobjc-arc
linker flag. This works all the way back to iOS 4.3.
Also check out the new Xcode Refactoring Assistant to convert your codebase to Modern Objective-C. It’s awesome.
Want to know more tips and tricks about iOS? Follow @steipete on Twitter.