首页 > 解决方案 > synthesize propertyname = _propertyname 有什么区别

问题描述

我是目标 c 的新手。我在类的 .h 头文件中创建一个属性,然后进行合成。

和有什么区别

@synthesize propertyname;

@synthesize propertyname = _propertyname;

两者都有效,但使用第一个或第二个的目的是什么。

任何帮助表示赞赏。

标签: iosobjective-c

解决方案


首先你不需要再写@synthesize propertyname了。

在 Objective-C 中,当你声明一个属性时,编译器默认会自动为你生成它的访问器方法。如果属性既是读取属性又是写入属性,则这些访问器方法可以是 getter 和 setter,否则如果它是只读属性,则只是 getter。

编译器在这些访问器方法实现的底层使用内部变量(称为 iVar)。(您显然可以提供您自己的这些访问器方法的实现,也可以提供您自己的内部变量)

@synthesize propertyname;和有什么区别@synthesize propertyname = _propertyname;

当您声明@synthesize propertyname;编译器时,自动生成并使用iVar命名propertyname并在其默认访问器实现中使用它,您也可以propertyname.m文件中使用它,因为编译器已经为您声明了它。

property = @"abcd";

当您声明@synthesize propertyname = _propertyname;编译器时,会自动生成并使用一个名为 iVar_propertyname并在其默认访问器实现中使用它,您也可以_propertyname.m文件中使用它,因为编译器已经为您声明了它。

_property = @"abcd";

从广义上讲,这两个语句之间的一般区别只是名称的变化iVar(虽然它的用法不同)

使用第一个或第二个的目的是什么。

正如我已经提到的,您不需要在正常用例中使用它们中的任何一个。编译器已经为你做到了。

We used to write @synthesize propertyname; when we neither had any specific reservation about the name of ivar nor wanted to provide our own private variable as ivar to a specific property (Explained in detail below). This was simpler than explicitly specifying the name of iVar and we knew that compiler will generate an ivar with same name as property for us.

we typically wrote @synthesize propertyname = _propetyname when @synthesize propertyname; wasn't available or when we wanted our iVar to follow a specific nomenclature ('_' following name of property) or when we wanted to use our own private variable as iVar to a property.

In both the cases @synthesize was handy because it would relieve us from writing a boiler plate code like adding setter and getter methods for properties declared.

如何将自定义变量用作ivar属性?

@interface SynthesizeExplorer : NSObject
@property (nonatomic,strong) NSString *name;
@end

@implementation SynthesizeExplorer
NSString *blaBlaName;
@synthesize name = blaBlaName;
@end

如果您查看,implementation您会看到该属性name由一个名为的内部变量支持,blaBlaName而不是由典型的编译器生成的 ivar(如nameor )支持_name

@synthesize到今天为止,我看到使用自定义内部变量来支持您声明的属性的唯一原因。否则我看不出任何书面意见@synthesize propertyname;@synthesize propertyname = _propertyname;


推荐阅读