Can someone explain this @synthesize syntax?

前端 未结 2 1056
[愿得一人]
[愿得一人] 2020-12-11 12:01

I\'m following the example Navigation View template with core data in the latest iOS SDK.

In the rootViewController.m file I see this in the @synthesize

2条回答
  •  时光取名叫无心
    2020-12-11 12:52

    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.

提交回复
热议问题