ios - synthesize propertyname = _propertyname 有什么区别
问题描述
我是目标 c 的新手。我在类的 .h 头文件中创建一个属性,然后进行合成。
和有什么区别
@synthesize propertyname;
和
@synthesize propertyname = _propertyname;
两者都有效,但使用第一个或第二个的目的是什么。
任何帮助表示赞赏。
解决方案
首先你不需要再写@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(如name
or )支持_name
。
@synthesize
到今天为止,我看到使用自定义内部变量来支持您声明的属性的唯一原因。否则我看不出任何书面意见@synthesize propertyname;
或@synthesize propertyname = _propertyname;
推荐阅读
- python - 有没有类似于 django 的 wordpress sensei 的技术?
- android-studio - Android Studio 项目中的不可读代码
- scala - Akka 流 Source.repeat 在 100 个请求后停止
- ios - 为什么应用程序包不总是一个包?
- java - 将 java Stream 转换为 Set
- c++ - 如何在另一个类函数中使用类,而与在 C++ 中声明的位置无关?
- javascript - 如何修复量角器中的错误“进程退出,错误代码为 1”?
- python - 如何使用 Windows 10 打开 Anaconda Navigator
- laravel - 集合中的项目总和字段
- python - 在 jupyter notebook 中远程录制音频