0

imagine my class declaration looks like this:

@interface MapViewController : UIViewController <MKMapViewDelegate>
{

}

@property (nonatomic,weak) IBOutlet MKMapView *mapV;

@end

This is implementation:

#import "MapViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface MapViewController ()

@end

@implementation MapViewController

@synthesize mapV;


- (void)viewDidLoad
{
    [super viewDidLoad];
    [mapV setShowsUserLocation:YES];
}

My question is, by using mapV as above (in viewDidLoad) am I referring to the instance variable or calling property? (what is the right way to refer to the instance variable in this case?).

user2054339
  • 393
  • 1
  • 6
  • 20

1 Answers1

2

If you use:

mapV

You are accesing the instance variable directly.

If you use:

self.mapV

You are accesing the variable trough the setter/getter, and those setter/getter are defined using the properties you set.

As a rule of thumb, you want to access you ivar directly in the init methods, and in the rest of the class you use self.

If you want to get more info on this, just follow this link:

Encapsulating data in Objective-C

Antonio MG
  • 20,382
  • 3
  • 43
  • 62
  • Hmm There's a book I am reading and in the `viewDidLoad` it also uses directly `[worldView setShowsUserLocation:YES];` -- however, in their case, the `worldView` is not a property, it is a instance variable directly. Is it OK like this? – user2054339 Jul 25 '13 at 08:24
  • It's not wrong, if the variable it's only accessed once, maybe the author preferred to not create the property, it's a personal choice depending on your code. I would always create the property if I'm accesing that variable more than in the init. – Antonio MG Jul 25 '13 at 08:26
  • I understand but if it is an ivar, then I can access it directly like this: `[worldView someMethod]`? e.g., no need to call `self`? – user2054339 Jul 25 '13 at 08:30
  • No, but accesing it like that you are not using the setter/getter that handles memory issues. If you have more doubts just follow this link: http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html – Antonio MG Jul 25 '13 at 08:31
  • But anyway, as it is in my question (where mapV is a property) is using `[mapV setShowsUserLocation:YES];` a mistake? – user2054339 Jul 25 '13 at 13:55
  • No, it's not a mistake, it's just recommended another way – Antonio MG Jul 25 '13 at 14:47