在使用 ARC 和针对 iOS4.0时,如何替换弱引用?

我已经开始用 Xcode 4.2开发我的第一个 iOS 应用程序,并且用一个“实用程序”模板(FlipsideViewController 附带的模板)瞄准 iOS 5.0。

我了解到由于 ARC 是一个编译时特性,它也应该与 iOS 4兼容,所以我试图将我的应用程序定位于4.3,并尝试编译它。当我这样做时,我得到这个错误:

Error: AutomativeReferenceCounting 問題: 當前部署目標不支援 Automated _ 孱弱引用

它指的是这句话:

@synthesize delegate = _delegate;

该变量声明为:

@property (weak, nonatomic) IBOutlet id <FlipsideViewControllerDelegate> delegate;

我知道 iOS4不支持“弱引用”,但是我真的不明白为什么一开始就要使用弱引用,我也不知道如何重写来避免使用它,同时还要利用 ARC (毕竟,它应该在 iOS4和5中工作,对吧

49933 次浏览

To target the older OS, you can use unsafe_unretained instead of weak in your property declaration, and it should mostly work the same way. weak references nil themselves when their target goes away, but unsafe_unretained leaves open the possibility that the object you're linking to could turn into a dangling pointer when it is deallocated. The latter is the same behavior as if you had used assign as a property declaration in manual memory management.

You do this to avoid retain cycles, which I mention in my answer here. You don't want to have a strong pointer to something that might have a strong pointer back to the original object. Then nothing would get released properly.

If only using weak references for additional safety, manually call the new runtime functions if they're available and fallback to simple assignment on __unsafe_unretained variables if not.

ZWRCompatibility.h will simplify this somewhat.

Thanks to Mike Ash's compatibility library PLWeakCompatibilty, you can now simply use __weak on iOS 4.x, as well.

It's incredibly easy to configure and requires no additional consideration or effort over 5.x.