Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

iphone - What exactly does @synthesize do?

I have seen the following piece of code:

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

//example.m
@synthesize mapView = mapView1

What is the relation between mapView and mapView1? Does it create a set and get method for mapView1?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...