As far as I understand @property declares the getter and setter in the .h file and @synthesize implements the getter and setter in the .m files. Furthermore it is possible to write your own implementation for the getter and setter instead of using @synthesize.
So if we always need to implement the setter/getter why do we need to additionaly declare it? @property seems to be semantical redundant to me and a source for bugs.
What happends when I declare a @property but forget to implement it with @synthesize or manually? What happends when I use @synthesize and forget the @property declaration?
Properties are now synthesized by default, since Xcode 4.4, so yes, you are right, it was redundant and Apple removed the need to write both @property and @synthesize, just use @property from now on.
having below in .h file
@property (retain, nonatomic) NSString* userName;
is syntactic sugar for
-(NSString*)userName;
-(void)setUserName:(NSString*)userName;
in the .h file
and @synthesize
in .m is syntactic sugar for leaving for its own implementation by respecting your retain
, nonatomic
, etc. as specified in your property declaration.
you cannot synthesize with out @property, even if you specified suitable getter, setter signature in .h file.
But you can leave @synthesize and implement your own getter and setter.
If you did both @synthesize and also your custom getter setter, run-time respects your implementation and call the same.
What happends when I declare a @property but forget to implement it with @synthesize or manually? What happends when I use @synthesize and forget the @property declaration?
Why don’t you try that? If you forget to synthesize the accessors or provide your own, the compiler will warn you. (And if you have it set to treat warnings as errors, which is a good idea, it’s impossible to miss the warning.) The second case will usually lead to a compile error.
So if we always need to implement the setter/getter why do we need to additionaly declare it? @property seems to be semantical redundant to me and a source for bugs.
To put it simply, @property
is a property declaration and @synthesize
is one possible implementation. One belongs to the header (= public interface description), the other to the implementation file. How would you do it if not this way?
Just wanted to add that you can also use @dynamic instead of @synthesize, although this is very rarely something you will need to do. @dynamic is basically telling the complier that you are somehow going to make sure that the calls to the getters and setters will be taken care of at run-time, either by making them yourself or by doing some extra messing around with some of the special features of the Objective C runtime.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With