Objective-C property and synthesize logic

In the earlier days of Obj-C and still today you declared variables in your class's header file like so:

@interface MySubclass : NSObject {
    int varName;
}

Then you would have to manually create setter and getter methods to access the variable outside your class. In order to help deal with memory management (useful for objects), Apple introduced properties in Obj-C 2.0 and it allowed you to define the accessors for a given variable. You could say that a variable would have certain attributes (such as retaining or copying a value, having alternate setter or getter name, etc) and you defined this like:

@property (someAttributes) int varName;

then in your @implementation you could @synthesize these properties with the given attributes and the compiler would generate setter and getter methods for your variable.

@synthesize varName; // Generates -setVarName: and -varName for you

Now, today the idea is that you can move away from implementing the instance variables in the {} section and just declare a property and a synthesize. What we get if we just say

@property (nonatomic) double topSpeed;
@synthesize topSpeed;

is a setter and a getter called setTopSpeed: and topSpeed with an instance variable called topSpeed (created by the compiler) to store the value. The idea behind @synthesize topSpeed = _topSpeed; is that the instance variable name will be _topSpeed but the accessor names will still be -setTopSpeed: and -topSpeed. This helps for code readability because there can be confusion between when you say self.topSpeed or topSpeed in your code (the first calls the accessor the second is the ivar). The _topSpeed differentiates itself from normal variables and also makes it explicit when you're calling self.topSpeed (the accessor) vs _topSpeed (the ivar). Apple is moving to this underscore syntax as well so don't think that it's going extinct, because it's quite the opposite. Update: (See Tommy's comment)

It also helps with variable naming collisions. If you had to implement setTopSpeed: yourself it would look something like this:

- (void)setTopSpeed:(double)topSpeed {
    _topSpeed = topSpeed; // _topSpeed makes it obvious it's an ivar
}

  1. It's a syntax sugar, let you type less word.
  2. Unlike java/c++, in obj-c you can't access variable of class. You could only call It's methods.
  3. @synthesize topSpeed = _topSpeed means You want an variable named _topSpeed and has Accessors named topSpeed and setTopSpeed.
  4. @property (nonatomic) double topSpeed; is not a pure variable declaration, It will also declare Accessors too. A pure variable of a class Foo will look like this :

    @interface Foo:NSObject{ double topSpeed; }