0

I'm following along with a Lynda.com OCUnit testing tutorial that uses XCode 4. In one of the demos, it synthesizes properties in a Location.m file like this

#import "Location.h"

@implementation Location

@synthesize locationManager=locationManager_;
@synthesize speed=speed_;

The properties have a trailing underscore. In other tutorials I've followed (such as the Stanford iOS class), the synthesized properties usually are prefixed with an underscore for the instance variables.

When the properties are created in the .h file, there are no underscores.

@property (nonatomic, strong) CLLocationManager *locationManager;
@property float speed;

Why the trailing underscore in the synthesize statement?

BrainLikeADullPencil
  • 11,313
  • 24
  • 78
  • 134

2 Answers2

2

By writing

@synthesize locationManager=locationManager_;

you are defining an ivar locationManager_which backs up your property.

So, to the property you still refer using

self.locationManager

However, ivar, "behind" that property is now called: locationManager_

  • 1
    I think it's a bad idea to have the underscore at the end, though, because it will make it more likely someone accidentally uses the ivar when they should be accessing the property, since autocomplete could more easily autocomplete to the ivar this way. That's why having the underscore at the beginning, the default behavior, is much preferred. Not a criticism of your answer, since that's how it is in the question as well, it's just a comment. :) – Gavin Mar 10 '14 at 18:17
  • 1
    @Gavin: I understand your comment, ok :). I rarely myself use ivars, prefer to always use self.propertyName for consistence (I know in rare cases in initializers you should prefer using ivars, but so far I have been doing like that) –  Mar 10 '14 at 18:21
  • I almost never use ivars directly either, and greatly prefer to use properties. The rare cases I will use ivars directly are generally in tight loops or in very performance-critical sections of code. Otherwise the overhead is minimal compared to the overhead of something like redrawing the screen. – Gavin Mar 10 '14 at 18:41
  • @Gavin: nb: seems apple discourages usage of properties in init methods ... http://stackoverflow.com/questions/4091062/using-properties-to-access-ivars-in-init –  Mar 10 '14 at 19:21
0

@synthesize allows you to specify the name of the ivar. The property is named locationManager but the ivar is named locationManager_.

NathanAldenSr
  • 7,841
  • 4
  • 40
  • 51