How do I replace weak references when using ARC an

2019-01-16 01:11发布

问题:

I've begun developing my first iOS app with Xcode 4.2, and was targeting iOS 5.0 with a "utility application" template (the one that comes with a FlipsideViewController).

I read that since ARC is a compile-time feature, it should be compatible with iOS 4 as well, so I attempted to target my app to 4.3, and try compiling it. When I do so, I get this error:

FlipsideViewController.m: error: Automatic Reference Counting Issue: The current deployment target does not support automated __weak references

It is referencing this line:

@synthesize delegate = _delegate;

That variable is declared as:

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

I understand that "weak references" are not supported in iOS 4, but I don't really understand why I would want to use a weak reference to begin with, nor can I figure out how I would rewrite things to avoid using it, while still taking advantage of ARC (after all, it's supposed to work with iOS 4 AND 5 right?)

回答1:

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.



回答2:

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.



回答3:

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.