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
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.
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