views:

208

answers:

5

I have seen the following piece of code:

//example.h
MKMapView * mapView1;
@property (nonatomic, retain) MKMapView * mapView;

//example.m
@synthesize mapView = mapView1

Question: What relation between mapView and mapView1 is ? Does it create set and get method for mapView1 ?

Thanks !

+5  A: 

Synthesize creates getter and setter for the variable.

Properties likes you specify some attributes for your variables, and when you synthesize that property to the variable, you generate the getter and setter for the variable.

The property name can be the same as the variable name. Sometimes, people want it to be different to use in init or dealloc or when the parameter is passed with the same variable's name

vodkhang
+4  A: 

From the documentation:

You use the @synthesize keyword to tell the compiler that it should synthesize the setter and/or getter methods for the property if you do not supply them within the @implementation block.

Dave DeLong
A: 

See the apple docs

Basically the synthesize creates a setMapView and mapView methods which set and get mapView1

Mark
A: 

It creates getter and setter for your object. You can access with something like this :

MKMapView* m = object.mapView;

or

object.mapView = someMapViewObject

mapView1 is the name of the ivar in the class, mapView is the name for the getter / setter.

Benj
+4  A: 

In your example, mapView1 is an instance variable (ivar), a piece of memory storage that belongs to an instance of the class defined in example.h and example.m. mapView is the name of a property. Properties are attributes of an object that can be read or set using the dot notation: myObject.mapView. A property doesn't have to be based on an ivar, but most properties are. The @propertydeclaration simply tells the world that there is a property called mapView.

@synthesize mapView = mapView1;

This line tells the compiler to create a setter and getter for mapView, and that they should use the ivar called mapView1. Without the = mapView1 part, the compiler would assume that the property and ivar have the same name. (In this case, that would produce a compiler error, since there is no ivar called mapView.)

The result of this @synthesize statement is similar to if you had added this code yourself:

-(MKMapView *)mapView
{
   return mapView1;
}

-(void)setMapView:(MKMapView *)newMapView
{
  if (newMapView != mapView1)
  {
    [mapView1 release];
    mapView1 = [newMapView retain];
  }
}

If you do add that code to the class yourself, you can replace the @synthesize statement with

@dynamic mapView;

The main thing is to have a very clear conceptual distinction between ivars and properties. They are really two very different concepts.

Felixyz
excellent explanation!
ennuikiller