Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 671
Gazzer Avatar asked Mar 02 '11 16:03

Gazzer


2 Answers

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

  1. avoid clashes with variable names and
  2. make it clear when I'm using a local variable and when I'm using an instance variable.
like image 129
kubi Avatar answered Oct 05 '22 06:10

kubi


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.

like image 42
mmalc Avatar answered Oct 05 '22 04:10

mmalc