当前位置:网站首页>【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方法的实现,还要自己写,属性还要自己定义。
边栏推荐
- CNN--各层的介绍
- 2022.07.12_Daily Question
- 2022.07.24_每日一题
- 解决win11/win10在登陆界面(解锁界面)点击获取每日壁纸无效的问题 - get Daily Lockscreen and Wallpaper - Win11/10的登录界面背景图片在哪里?
- 2022.07.20_Daily Question
- MySQL安装到最后一步 write configuration file 失败 怎么办?及后安装步骤
- 文件 - 04 下载文件: 根据文件下载链接下载文件
- The Perfect Guide|How to use ODBC for Agentless Oracle Database Monitoring?
- 任务及任务切换
- 2022.07.20_每日一题
猜你喜欢
文件 - 05 下载文件:根据文件Id下载文件
2. (1) Chained storage of stack, operation of chain stack (illustration, comment, code)
【微服务】Nacos集群搭建以及加载文件配置
【Go报错】go go.mod file not found in current directory or any parent directory 错误解决
Linked list implementation and task scheduling
【Go】Go 语言切片(Slice)
【Go语言入门】一文搞懂Go语言的最新依赖管理:go mod的使用
Financial leasing business
解决win11/win10在登陆界面(解锁界面)点击获取每日壁纸无效的问题 - get Daily Lockscreen and Wallpaper - Win11/10的登录界面背景图片在哪里?
【愚公系列】2022年07月 Go教学课程 022-Go容器之字典
随机推荐
One of the small practical projects - food alliance ordering system
电压源的电路分析知识分享
2704:寻找平面上的极大点
第9章 异常try...except...else...finally
【Star项目】小帽飞机大战(八)
2022.07.12_每日一题
【微服务】(十六)—— 分布式事务Seata
Log4net 思维导图
【Go语言入门】一文搞懂Go语言的最新依赖管理:go mod的使用
Postgresql source code learning (34) - transaction log ⑩ - full page write mechanism
【Star项目】小帽飞机大战(七)
那些破釜沉舟入局Web3.0的互联网精英都怎么样了?
Automatic translation software - batch batch automatic translation software recommendation
tidyverse笔记——管道函数
2022.07.22_每日一题
leetcode 406. Queue Reconstruction by Height
简单谈谈Feign
【第四章】详解Feign的实现原理
2022.07.26_Daily Question
知识、创新、回报。