Integrating non-ARC source into an ARC project

There is little to no reason to not be using Apple’s Automatic Reference Counting (unless your product is truck in an ancient runtime – pre iOS 4 and OS X 10.6). But, if you have some legacy code that gets compiled into an ARC enabled project, here’s a little trick using C macros (you can name them whatever you want, we use the WB, for “Wooly Beast”, prefix):

#ifndef WBRetain
#if __has_feature(objc_arc)
# define WBRetain(obj) obj
#else
# define WBRetain(obj) [obj retain]
#endif
#endif

#ifndef WBRelease
#if __has_feature(objc_arc)
# define WBRelease(obj)
#else
# define WBRelease(obj) [obj release], obj = nil
#endif
#endif

#ifndef WBAutorelease
#if __has_feature(objc_arc)
# define WBAutorelease(obj) obj
#else
# define WBAutorelease(obj) [obj autorelease]
#endif
#endif

Some examples of usage:

// an autoreleased object
MyObject *obj = WBAutorelease([[MyObject alloc] init]);

// a manually released object
MyObject *obj = [[MyObject alloc] init];
// do stuff...
WBRelease(obj);

For easy cut-and-paste, check out the gist.

Tags: , , , , , , ,

Leave a Reply