Converting an iOS Project to use ARC (Automatic Reference Counting)
Recently I went through the process of converting a few non-ARC projects and bringing them into the exciting world of ARC. Before ARC was introduced for iOS 5 in 2011, the core Mobile Team here at Object Partners Inc. had become comfortable and proficient dealing with Objective-C Memory Management. Managing memory and paying attention to object ownership was a part of life in Objective-C and we accepted it.
However, once we got exposed to ARC and the cleaner code it produced it was difficult to go back to older projects that were developed pre-ARC. At OPI we have always followed a disciplined approach for maintaining a stable, reusable iOS foundation that is relied on for all app development. Unfortunately, most of the foundation code is non-ARC and switching from ARC to non-ARC takes all the fun out of developing iOS apps.
Below represents my experience converting a recent project to use ARC. I hope most of it will help in your project conversions, but it is not meant to be an exhaustive list of findings either.
* XCode 4.6.3 was used for this exercise.
Initial Conversion Using XCode
Before you start make sure you create a backup of your project. We use GitHub for all our codebases so to do this we simply tagged the project codebase in GitHub and branched before we started.
XCode’s ARC Conversion Tooling does a nice job leading you through the conversion process. This article at www.daveoncode.com explains the basics for using this tool. To summarize the steps in XCode from the article:
- “Preferences” -> “General” -> check “continue building after error”. This step is fundamental to avoid an huge waste of time repeating the next steps every time an error is encountered!
- “Edit” -> “Refactor” -> “Convert to Objective-C ARC”
- “Select targets to convert” (check them)
- Click “precheck” – “Cannot Convert to Objective-C ARC” (Xcode found N issues that prevent conversion from proceeding. Fix all ARC readiness issues and try again.) You will see this message at least once, because your code contains calls that are forbidden by ARC.
- Fix them using suggestions (click on errors to open the popup containing the tip). Then repeat from step 1.
- “Convert to automatic reference counting” window will appear (once issues have been fixed)
- Click next
- Review automatic changes
- Save
Done!!
Post Conversion Checks
Congratulations you have converted to ARC! But do not get too excited. Once I converted my project and tested it for the first time it did not go as smoothly as I would have liked. Maybe this was a good thing since it forced me to re-visit some of my old coding practices and bring them into the ARC era. Here are a few things I encountered and what I did to them fix in my codebase. The good news is fixing these was quite painless.
Converting @property(non-atomic, readonly) to ARC
This one resulted in unretained references that would result in app crashes. When XCode converted these properties to ARC the code style I was using to ensure I had proper retain cycles for readonly properties broke. Here is what I did to fix it – by example:
Pre-ARC
@interface GridLayout : NestedLayout { NSMutableArray *rows; } @property (nonatomic, readonly) NSMutableArray *rows; ... @implementation GridLayout @synthesize rows; - (id) init { self = [super init]; if (self) { // Retain instance for readonly rows rows = [[NSMutableArray arrayWithCapacity:0] retain]; } return self; } ...
Post-ARC Conversion
@interface GridLayout : NestedLayout { NSMutableArray *rows; } @property (nonatomic, __unsafe_unretained, readonly) NSMutableArray *rows; ... @implementation GridLayout @synthesize rows; - (id) init { self = [super init]; if (self) { // Retain instance for readonly rows rows = [NSMutableArray arrayWithCapacity:0]; } return self; } ...
Fixed Code
If you look carefully at the converted code above you will see that XCode removed my retain reference for this property. To ensure safe access of this property and the fact I did not really need this field to be readonly I modified the code to strictly use property accessors. NOTE: if I wanted to maintain the readonly attributes of the property I would have had to add the retain code back in.
@interface GridLayout : NestedLayout @property (nonatomic, strong) NSMutableArray *rows; ... @implementation GridLayout @synthesize rows = _rows; - (id) init { self = [super init]; if (self) { // Retain instance for readonly rows self.rows = [NSMutableArray arrayWithCapacity:0]; } return self; }
All is now well with the retains.
ARC weak vs __unsafe_unretained
XCode converted all weak referenced objects in my code to __unsafe_unretained. For more info on ARC ownership qualifiers this article provides a nice explanation. Since my project is targeted for iOS 5 and higher I replaced all __unsafe_unretained keywords with weak.
Bridge Casting
A bridged cast is a C-style cast required in order to transfer objects in and out of ARC control. Please refer to ARC Documentation for details.
Bridge casting is required before XCode can convert your code, but it does a nice job finding all the places in your code you have to fix before continuing.
Here is an example of a casting between C-style references and Objective-C classes:
Pre-ARC
CFPropertyListRef plist = CFPropertyListCreateFromXMLData(kCFAllocatorDefault, (CFDataRef)data, kCFPropertyListImmutable, NULL); return [(NSDictionary *)plist autorelease];
Post-ARC
CFPropertyListRef plist = CFPropertyListCreateFromXMLData(kCFAllocatorDefault, (__bridge CFDataRef)data, kCFPropertyListImmutable, NULL); return (NSDictionary *)CFBridgingRelease(plist);
@autoreleasepool is Your Friend
When you have loops in your code (for, while, etc) that allocate memory with every iteration you should be using @autoreleasepool so the memory is released after every iteration as opposed to and the end of the looping logic.
I ran into a few places where before I was releasing memory explicitly after each loop iteration yet after the ARC conversion the code was not releasing any memory until after all iterations in the loop completed. This is where the @autoreleasepool came to the rescue.
Pre-ARC
SomeObject *obj = nil; for (int i=0; i < 1000; i++) { obj = [SomeObject alloc] init]; // Do stuff [obj release]; obj = nil; }
Post-ARC
SomeObject *obj = nil; for (int i=0; i < 1000; i++) { @autoreleasepool { obj = [SomeObject alloc] init]; // Do stuff obj = nil; } }
Final Words
Well this concludes my experience with converting a project to be fully ARC compliant. I am now much more confident and encourage a full embrace of ARC on all projects. Having gone through this conversion process I discovered it was relatively painless. After reading this I hope you are ready to get started.
thanks! Nice write up, went a lot easier than I expected. One thing you might want to add, if you have libraries that don’t support ARC, you can add the -fno-objc-arc before doing the refactor to exclude those files from the script. Although the flags will be stripped out after completing the process.
Good point thanks Andrew. I also found the process went smoother than I thought. That is one of the reasons I wrote this blog post. Thanks for leaving a comment!!
Thank you for this. Still have not converted to ARC, but I have many project that need it. This gives me some hope and confidence that it may not be as painful as I thought.