ios non-arc to arc 之三

本文介绍了一位开发者将非ARC项目转换为使用自动引用计数(ARC)的过程。通过Xcode工具进行初步转换,并修复了转换过程中出现的问题,包括属性声明、弱引用和桥接转换等。此外还分享了一些最佳实践,如使用@autoreleasepool来管理内存。

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;
	}
}
乐播投屏是一款简单好用、功能强大的专业投屏软件,支持手机投屏电视、手机投电脑、电脑投电视等多种投屏方式。 多端兼容与跨网投屏:支持手机、平板、电脑等多种设备之间的自由组合投屏,且无需连接 WiFi,通过跨屏技术打破网络限制,扫一扫即可投屏。 广泛的应用支持:支持 10000+APP 投屏,包括综合视频、网盘与浏览器、美韩剧、斗鱼、虎牙等直播平台,还能将央视、湖南卫视等各大卫视的直播内容一键投屏。 高清流畅投屏体验:腾讯独家智能音画调校技术,支持 4K 高清画质、240Hz 超高帧率,低延迟不卡顿,能为用户提供更高清、流畅的视觉享受。 会议办公功能强大:拥有全球唯一的 “超级投屏空间”,扫码即投,无需安装。支持多人共享投屏、远程协作批注,PPT、Excel、视频等文件都能流畅展示,还具备企业级安全加密,保障会议资料不泄露。 多人互动功能:支持多人投屏,邀请好友加入投屏互动,远程也可加入。同时具备一屏多显、语音互动功能,支持多人连麦,实时语音交流。 文件支持全面:支持 PPT、PDF、Word、Excel 等办公文件,以及视频、图片等多种类型文件的投屏,还支持网盘直投,无需下载和转格式。 特色功能丰富:投屏时可同步录制投屏画面,部分版本还支持通过触控屏或电视端外接鼠标反控电脑,以及在投屏过程中用画笔实时标注等功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值