I’m using AppCode and it flagged an interesting situation in the code of a very large project. Pre-ARC.
A subclass defines and synthesizes a property called delegate. Actually the property declaration had been commented out! But the @synthesize delegate = delegate_; statement was left behind.
The code compiles, presumably because the base class defines and synthesizes a property also called delegate and synthesizes it with a backing variable with the same name: @synthesize delegate = delegate_;
My question is: What happens with a message is sent to the delegate in
a) the base class methods and
b) in the sub-class methods.
AppCode flags the synthesize statement in the sub-class as an error:
Accessors of property ‘delegate’ were already synthesized with
instance variable ‘delegate_’
The
@synthesizedirective is shorthand for creating accessor methods and an ivar according to the specifications (atomicity, memory management) of the property of the same name. Given that, re-synthesizing a property in a subclass (without re-declaring it) works exactly like overriding the accessor methods — the subclass’s implementations are used instead of the superclass’s. Since the implementations are created by the compiler in both cases, there’s no noticeable difference in behavior.The one difference is that a synthesized ivar has the same visibility as a
@privateivar, so subclasses can’t access it, including to use it as the backing variable for a property. This means that the re-synthesis in the subclass must use a different ivar name. If the superclass has@synthesize wildHorses = wildHorses_;, then the compiler requires the subclass to do something like@synthesize wildHorses = equusFerus;.**If the superclass uses the default name for the created ivar,
@synthesize wildHorses;then the subclass must still synthesize a new variable:@synthesize wildHorses = wildHorses_;