Reputation: 13
Lets assume I have a class ClassA
header:
@interface ClassA : NSObject
- (id)initWithDelegate:(id)delegate;
@end
implementation:
@interface ClassA ()
{
NSObject *_delegate;
}
@end
@implementation
- (id)initWithDelegate:(id)delegate
{
self = [super init];
if( self )
{
_delegate = delegate;
}
return self;
}
@end
Since I skipped the @property definition my delegate declaration defaults to strong? So this code is wrong because it will cause a leak, or does my delagate declaration default to weak?
Upvotes: 0
Views: 74
Reputation: 1557
You are correct, this will cause ARC to retain the _delegate, ie make a "strong" reference. If you want to create a weak reference without declaring a @property
, you can use
@interface ClassA ()
{
__weak id _delegate;
}
@end
Upvotes: 0
Reputation: 17143
You do have to qualify that ivar as __weak. The default for an ivar is strong.
Otherwise, as you already know, you risk a retain cycle with delegates.
BTW, the convention here is 'id' rather than NSObject *.
Upvotes: 1
Reputation: 104065
It’s best to write the code in a way that makes this explicit:
@interface ClassA : NSObject
@property(weak) id delegate; // or @property(weak, readonly)
@end
@implementation ClassA
- (id)initWithDelegate: (id) delegate
{
self = [super init];
_delegate = delegate;
return self;
}
@end
By default, you instance variable would be strong.
Upvotes: 0