Search code examples
objective-cautomatic-ref-countingweakunsafe-unretained

ObjC automatic reference counting(ARC): weak vs assign vs unsafe_unretained for delegate?


I have a class:

@interface MyClass : NSObject
@property (weak) id delegate;
@end

and the implementation:

@implementation MyClass
@synthesize delegate;
@end

When I refactor the code for ARC, it tells me that synthesize of 'weak' property is only allowed in ARC/GC mode. But from what I known, delegate can be 'weak' in ARC, also, if I change it to assign, then it will be converted to unsafe_unretained.

My question is, does it mean the code before conversion(to ARC) should NOT use anything ARC?

Thanks!


Solution

  • It sounds like you might be targeting iOS 4.x

    4.x added ARC, but not the full ARC that iOS5+ got. iOS 4.x arc doesn't have support for the "weak" keyword, only unsafe_unretained. If you want to use weak instead of unsafe_retained you will have to drop iOS 4 support.

    The difference between "weak" and "unsafe_unretained" is that weak will set itself to nil when it is released, where as unsafe_unretained will hang around pointing to bad (released) memory.