Mixing ARC and MRC source code in the same class

The Automated Reference Counting (ARC) mechanism was introduced with iOS 5 to make developer’s life easier. Until iOS 5 the developer had to manually keep track of the number of references (Manual Reference Counting or MRC) to every allocated object and release correctly it after that object was not anymore needed.

So, for example, before iOS 5, you had to write something like this:

The last line of code was necessary to release the anArray object and avoid a memory leak. When you use ARC, the previous 3 lines of code become:

This is really cool because developers no longer need to keep track of the number of references to the allocated object, and also, more importantly, developers can now write less code. Much like iNVASIVECODE’s specialized consulting, this change allows developers to streamline their development and increase effectiveness.

Let’s make clear this too. ARC is NOT a runtime mechanism. It has nothing to do with the Garbage Collection previously available in Cocoa (Mac) and still available in Java and other languages. ARC is a compiler level feature that automatically inserts the release and retain during the compilation phase.

Now, to keep backward compatibility with old MRC code you can mark in Xcode those files you want ARC to ignore. But you can also mix in the same class ARC and MRC code, using the __has_feature compiler macro. This macro is part of Clang, part of LLVM. For more information about LLVM, you should absolutely check this website: http://llvm.org.

So, for example, imagine you are building next killer iOS app and using ARC in your project. It could be you need to integrate quickly some MRC code you got from Github or somewhere else. Yes, sure you can convert that code to ARC, but maybe it’s faster if you do this:

And if you need you can obviously also do this:

If you want ARC to exclude an entire class file (the .m), you need to go to Target Build Phases and in the Compiler Sources you add the -fno-objc-arc flag as shown in the following figure:

Keep coding,

Geppy

iOS Consulting | INVASIVECODE

iOS Training | INVASIVECODE

(Visited 90 times, 1 visits today)