当前位置:网站首页>【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方法的实现,还要自己写,属性还要自己定义。
边栏推荐
- codec2 BlockPool:不可读库
- Run the NPM will pop up to ask "how are you going to open this file?"
- navicat 新建数据库
- Chapter 17: go back to find the entrance to the specified traverse, "ma bu" or horse stance just look greedy, no back to search traversal, "ma bu" or horse stance just look recursive search NXM board
- 超级详细的mysql数据库安装指南
- 2022.07.14_每日一题
- Difficulty comparison between high concurrency and multithreading (easy to confuse)
- 2022.07.12_每日一题
- Postgresql source code learning (33) - transaction log ⑨ - see the overall process of log writing from the insert record
- HighTec 的安装与配置
猜你喜欢
随机推荐
opencv、pil和from torchvision.transforms的Resize, Compose, ToTensor, Normalize等差别
[PSQL] 复杂查询
tidyverse笔记——管道函数
Web浏览器工作流程解析
【第四章】详解Feign的实现原理
Postgresql source code learning (34) - transaction log ⑩ - full page write mechanism
[PSQL] SQL基础教程读书笔记(Chapter1-4)
Zabbix6.2惊喜发布!特别优化中大型环境部署的性能!
Fund investment advisory business
知识、创新、回报。
'vite' is not an internal or external command, nor is it a runnable program or batch file.
手把手教你开发微信小程序自定义底部导航栏
2022.07.20_Daily Question
Obtaining server and client information
2022.07.24_每日一题
测试 思维导图
Automatic translation software - batch batch automatic translation software recommendation
基于交替迭代法的交直流混合系统潮流计算matlab程序iEEE9节点系统算例
360 push-360 push tool-360 batch push tool
Run the NPM will pop up to ask "how are you going to open this file?"