When declaring a property you are declaring the setter/getter for a instance variable
No, you are declaring a getter and possibly a setter of a property. Period. Declaring a property does not itself imply an instance variable. There are many ways to implement a property. Instance variables happen to be a common and popular way, but non-ivar properties are very common.
If you want to have the setter and getters defined you need to synthesize them
No. (As sergio points out, I originally confused "defined" and "declared.") Almost. The @property
line itself declares the setter and getter. If you want to have the setter and getter implemented for you, that is called "synthesize," but you no longer need to do this manually. The complier will automatically create a getter and setter for any property that you declare but do not implement (unless you explicitly ask it not to using @dynamic
).
If you synthesize, the instance variable is defined for you. Best practice is to rename the iVar so that the getter and iVar aren't the same name. So you usually do: @synthesize myVar = _myVar
Almost. This was true a few months ago, but you no longer need to actually do that @synthesize
. It will be done automatically for you by the compiler now.
This header:
@interface MyObject : NSObject
@property (nonatomic, readwrite, strong) NSString *something;
@end
is almost the same as this header:
@interface MyObject : NSObject
- (NSString *)something;
- (void)setSomething:(NSString *)something;
@end
There are some very small differences between these two, some related to the runtime and some related to the compiler, but it is clearer if you just pretend they're identical.
All you're doing in both of these cases is declaring some methods. You are not declaring how they're implemented. You're not declaring ivars. You're just declaring methods. You are now free to implement those methods any way you like. If you like, you can implement them by letting the compiler synthesize some default implementations for you. If you like you can implement them by hand. You can do one of each if you like.