synthesize究竟做了什么

synthesize究竟做了什么

本文介绍了@synthesize究竟做了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过以下代码:

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

//example.m
@synthesize mapView = mapView1

问题: mapView mapView1 之间有什么关系?
是否为 mapView1 创建设置获取方法?

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

谢谢!

推荐答案

在您的示例中, mapView1 实例变量(ivar),一段内存存储,属于 example.h 示例中定义的类的实例。米 mapView 属性的名称。属性是可以使用点表示法读取或设置的对象的属性: myObject.mapView 。一个属性不 基于ivar,但大多数属性都是。 @property 声明只是告诉全世界有一个名为 mapView 的属性。

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;

这一行告诉编译器创建一个setter和 mapView 的getter,以及他们应该使用名为 mapView1 的ivar。如果没有 = mapView1 部分,编译器将假定属性和ivar具有相同的名称。 (在这种情况下,这将产生编译器错误,因为没有名为 mapView 的ivar。)

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.)

@synthesize 语句的结果与您自己添加此代码类似:

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替换 @synthesize 语句;

@dynamic mapView;

主要是在ivars和属性之间有一个非常明确的概念区别。它们实际上是两个非常不同的概念。

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

这篇关于@synthesize究竟做了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 08:55