I understand that @synthesize window;
combined with @property
\'auto-creates\' your setters and getters, but I\'m not sure exactly what happens whe
The syntax is described in the documentation -- see Property Implementation Directives.
The reason for changing the instance variable name is precisely to discourage direct access. An underscore is used by convention. (Note: Although the Coding Guidelines currently warn against using an underscore, this advice is out-of-date.)
Again per the documentation (see Using Accessor Methods), apart from init and dealloc methods, you should always use accessor methods. You use set accessors to ensure that you manage memory correctly, and that you emit KVO change notifications if appropriate. You use get accessors to ensure that the property is correctly initialised. There are several common places where properties are initialised lazily; if you don't use the accessor, you get nil...
An example of direct access: Using one of the Core Data templates, if you used:
NSFetchRequest *request = ...;
NSError *error = nil;
NSArray *results = [__managedObjectContext executeFetchRequest:request error:&error];
instead of
NSArray *results = [self.managedObjectContext executeFetchRequest:request error:&error];
then -- because the managed object context is created lazily in the accessor method -- you might end up sending a message to nil and getting no results.
Your properties almost always have a backing variable. What
@synthesize searchBar = _searchBar;
does is declare that the backing variable for your search bar will be called _searchBar
. This allows you to decouple the name of the property from the name of your variable. In fact, if you don't use @synthesize
you don't need to have a backing variable at all.
As for why people do this, everyone has different reasons. Personally, I do it to
@synthesize searchBar = _searchBar;
says to make a getter method named "searchBar" (etc.) for the instance variable _searchBar.
The underscore on the _searchBar variable usually means "Don't access me directly unless you really know what you're doing. Please use the getter and setter methods instead!".