当前位置:网站首页>【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方法的实现,还要自己写,属性还要自己定义。
边栏推荐
猜你喜欢

Zabbix6.2惊喜发布!特别优化中大型环境部署的性能!

Foreign trade website optimization - foreign trade website optimization tutorial - foreign trade website optimization software

2022.07.20_Daily Question

Conditional statements of shell (test, if, case)

完美指南|如何使用 ODBC 进行无代理 Oracle 数据库监控?

机器学习---线性回归、Logistic回归问题相关笔记及实现

SCI写作指南

基于交替迭代法的交直流混合系统潮流计算matlab程序iEEE9节点系统算例

我开发了一个利用 Bun 执行 .ts / .js 文件的 VS Code 插件

【面试:并发篇38:多线程:线程池】ThreadPoolExecutor类的基本概念
随机推荐
【 TA - frost Wolf _may - "one hundred plan" 】 art 2.3 hard surface
基于交替迭代法的交直流混合系统潮流计算matlab程序iEEE9节点系统算例
【Go】Go 语言切片(Slice)
2022.07.18 _ a day
2022.07.15_每日一题
One of the small practical projects - food alliance ordering system
Bulk free text translation
Zabbix6.2惊喜发布!特别优化中大型环境部署的性能!
从入门到一位合格的爬虫师,这几点很重要
'vite' is not an internal or external command, nor is it a runnable program or batch file.
[PSQL] 复杂查询
2022.07.15_Daily Question
SQL Server Datetime2数据类型
2022.07.13 _ a day
mysql的建表语句_三种常用的MySQL建表语句
2022.07.12_每日一题
Financial leasing business
DAY18:Xss 靶场通关手册
科普 | “大姨太”ETH 和 “小姨太”ETC的爱恨情仇
2022.07.29_每日一题