Can someone explain this @synthesize syntax?

偶尔善良 提交于 2019-11-28 12:59:37

Only the first one (on the lhs of the synthesize statement) is synthesized with a getter and setter and becomes the "public" instance variable.

The latter (with the underscore) is still available inside the instance but is not exposed outside the instance. They both reference the same memory address.

In the @synthesize syntax, the left side of the = (which is just a character the synthesize uses for this syntax, not the assignment operator) is the name of the property (and associated methods), and the right side of the = is the instance variable to use for the named property.

In the above example, @synthesize fetchedResultsController=fetchedResultsController_ creates a fetchedResultsController getter method and a setFetchedResultsController: setter method, both using the fetchedResultsController_ instance variable for storage. 

Likewise, @synthesize managedObjectContext=managedObjectContext_ creates managedObjectContext and setManagedObjectContext: accessor methods, both backed by the managedObjectContext_ instance variable.

If the “right sides” had not been explicitly specified (if the declaration read @synthesize fetchedResultsController, managedObjectContext;), synthesize would've assumed the same name for the instance variable as the property.  Some Objective-C programmers dislike leaving it at this default behaviour because it can be easy to make the mistake of intending to set local function-scope variable and instead setting an instance variable instead.  Using an underscore for all instance variables makes their intent clearer.

Just to be clear, multiple @synthesize properties can be combined into one by comma separating; each is still its own declaration such that the above is fully equivalent to:

@synthesize fetchedResultsController=fetchedResultsController_;
@synthesize managedObjectContext=managedObjectContext_;

Also worth nothing, in newer Xcode/iOS versions instance variables will be created automatically if not explicitly defined, and @synthesize declarations are also assumed if not specified.  These differences are explained in Apple's quick-ref Objective-C Feature Availability Index.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!