What does @synthesize window=_window do?

后端 未结 3 1463
感动是毒
感动是毒 2020-11-27 17:35

I understand that @synthesize window; combined with @property \'auto-creates\' your setters and getters, but I\'m not sure exactly what happens whe

3条回答
  •  青春惊慌失措
    2020-11-27 17:52

    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.

提交回复
热议问题