What does @synthesize window=_window do?
I understand that @synthesize window;
combined with @property
'auto-creates' your setters and getters, but I'm not sure exactly what happens when you assign a value like
@synthesize searchBar = _searchBar;
Does this mean that I can simply use _searchBar instead in my methods rather than say self.searchBar ?
Is it to prevent a clash of ivar names for instance with this delegate method:
- (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
Is it the equivalent of self.searchBar
rather than searchBar
or are those two identical anyway?
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
- avoid clashes with variable names and
- make it clear when I'm using a local variable and when I'm using an instance variable.
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.
@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!".