1

When you create a property and the compiler auto-synthesizes an underlying ivar, does the ivar have the same retain semantics has the property, or do the retain semantics only apply to the "setter"?

@property (nonatomic, strong) NSObject *strongObject
@property (nonatomic, weak)   NSObject *weakObject

_strongObject = [[NSObject alloc] init];    // is this strong?
_weakObject =   [[NSObject alloc] init];    // is this weak?
Steveo
  • 2,238
  • 1
  • 21
  • 34

1 Answers1

1

Check this question. It seems that the underlying variable has the same semantics as the property, assuming you're using ARC. You could override a setter to a strong property like this:

- (void)setMyObject:(MyObject *)anObject
{
   _myObject = anObject;
}

This means that you don't have to release before (like in non-ARC) because ARC handles this at the ivar level (see here).

However this is not true if not using ARC, for example assign and retain, are NOT valid for ivars, only for the properties.

Community
  • 1
  • 1
Merlevede
  • 8,140
  • 1
  • 24
  • 39
  • Does this also mean that a direct ivar assignment with copy semantics will in fact do a copy? Take this example: `@property (nonatomic, copy) NSString *myString;` Custom setter looks like `if (_myString == nil) _myString = @"A"; return _myString;` – Steveo Feb 21 '14 at 16:48
  • Hmm it looks weird (specially the return statement for a setter), but no, you need to copy it explicitly. ARC handles the retain count, not the copy operation. – Merlevede Feb 21 '14 at 17:17
  • My bad. Return statement shouldn't have been there. – Steveo Feb 24 '14 at 18:35