ios non-arc to arc 之三

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:

  1. “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!
  2. “Edit” -> “Refactor” -> “Convert to Objective-C ARC”
  3. “Select targets to convert” (check them)
  4. 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.
  5. Fix them using suggestions (click on errors to open the popup containing the tip). Then repeat from step 1.
  6. “Convert to automatic reference counting” window will appear (once issues have been fixed)
  7. Click next
  8. Review automatic changes
  9. 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;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值