当前位置:网站首页>【Objective-C语言中的@property】
【Objective-C语言中的@property】
2022-07-31 06:28:00 【清风清晨】
前言
我们写一个类,分以下几个步骤:
1)要先为类写属性
2)再声明属性的getter 和 setter方法
3)再实现这个getter和setter
有没有让编译器自动实现这些代码的方法?
答案是,有,天空一声巨响,@property就隆重登场了!
一、@property的作用是什么?
1)作用:自动生成getter和setter方法的声明
因为是生成方法的声明,所以应该写在@interface类的声明里面。
2)语法:@property 数据类型 名称;
比如,有一个Person类:
@interface Person : NSObject
{
NSStrin *_name;
int _age;
}
– (void)setName:(NSStrin *)name;
– (NSString *)name;
@property int age;
@end
@implementation Person
– (void)setName:(NSString *)name
{
_name = name;
}
– (NSString *)name
{
return _name;
}
@end
上述代码中的@property int age,这句话有什么效果?
1)它自动的生成getter和setter方法的声明
2)它的原理:
编译器在编译的时候,会根据@property生成getter和setter方法的声明:
@property 数据类型 名称;
这句话会被编译器转换为:
- (void)set首字母大写的名称:(数据类型)名称;
- (数据类型)名称;
例如:
@property int age;
会被编译器自动转换为以下两个语句:
- (void)setAge:(int)age;
- (int)age;
再比如,我们想让@property自动生成以下两句代码:
- (void)setName:(NSString *)name;
- (NSString *)name;
怎么做?只需写出如下一句代码:
@property NSString *name;
二、使用@Property的注意:
1.数据类型和属性的数据类型一致
例如,@property float height;
[email protected]的名字和属性的名字一致,但是要去掉下划线
例如,@property float weight;
[email protected]的名称决定了我们这个getter和setter方法的名称
[email protected]的数据类型决定了setter方法的参数类型,和getter方法的返回值类型
总结
@property自动生成getter和setter方法的声明,但是getter和setter方法的实现,还要自己写,属性还要自己定义。
边栏推荐
猜你喜欢
Conditional statements of shell (test, if, case)
Zabbix6.2 Surprise Release!Especially optimize the performance of medium and large environment deployment!
【解决】mysql本地计算机上的MySQL服务启动后停止。某些服务在未由其他服务或程序使用时将自动停止
客户端navicat安装教程
'vite' is not an internal or external command, nor is it a runnable program or batch file.
Financial leasing business
那些破釜沉舟入局Web3.0的互联网精英都怎么样了?
Yu Mr Series 】 【 2022 July 022 - Go Go teaching course of container in the dictionary
DAY18: XSS vulnerability
《白帽子说Web安全》思维导图
随机推荐
The Perfect Guide|How to use ODBC for Agentless Oracle Database Monitoring?
R——避免使用 col=0
基金投顾业务
sort函数(快速排列)的使用方法
文件 - 05 下载文件:根据文件Id下载文件
2022.07.13 _ a day
Zotero | Zotero translator plugin update | Solve the problem that Baidu academic literature cannot be obtained
从入门到一位合格的爬虫师,这几点很重要
【 TA - frost Wolf _may - "one hundred plan" 】 art 2.3 hard surface
2022.7.29 Array
Zabbix6.2惊喜发布!特别优化中大型环境部署的性能!
Zabbix6.2 Surprise Release!Especially optimize the performance of medium and large environment deployment!
文件 - 02 上传文件:上传临时文件到服务器
毫米波技术基础
Obtaining server and client information
Tasks and task switching
Linked list implementation and task scheduling
【微服务】 微服务学习笔记二:Eureka注册中心的介绍及搭建
熟悉而陌生的新朋友——IAsyncDisposable
DAY18: Xss Range Clearance Manual