当前位置:网站首页>【Objective-C中的@synthesize】
【Objective-C中的@synthesize】
2022-08-01 21:19:00 【清风清晨】
前言
@property只能生成getter和setter方法的声明,那实现怎么办呢?
一、@synthesize是什么?
比如,有一个类
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
NSString *_name;
int _age;
float _weight;
}
@property NSString *name;
@property int age;
@property float weight;
@end
@implementation Person
@end
那么,getter和setter方法的实现,能不能自动生成呢?
1)@synthesize的作用:自动生成getter和setter方法的实现。
2)语法:@synthesize @property的名称;
例如:
@interface Person : NSObject
{
int _age;
}
@property int age;
@end
----------------------
@implementation Person
@synthesize age;
@end
二、@synthesize做的事情
1.生成一个真私有的属性
1) 什么叫真私有的属性,也就是声明在@implementation之中的,
2)这个属性的类型和@synthesize对应的@property类型一致;
3)属性的名字和@synthesize对应的@property名字一致;
例如,这段代码:
@implementation Person
@synthesize age;
@end
转换为
@implementation Person
{
int age;
}
- (void)setAge:(int)age;
{
self->age = age;
} - (int)age
{
return age;
}
@end
4)自动生成setter方法的实现
实现的方式:直接把参数age的值传递给它生成的那个私有属性age;
5)自动生成getter方法的实现
实现的方式:返回它自动生成的那个私有属性的值
2.如何让@synthesize不要自动生成私有属性,就用我们自己定义的带下划线的属性,就行了
语法:@synthesize @property名称 = 已经存在的属性名;
例如:@synthesize age = _age;
那么,这句话它是什么意思呢?
1)不再生成私有属性;
2)直接生成getter和setter方法的实现;
3)setter怎么实现的呢?把参数的值赋值给已经存在的下划线属性
例如:
- (void)setAge:(int)age
{
_age = age;
}
4)getter怎么实现的呢?直接返回已经存在的下划线属性的值。
- (int)age
{
return _age;
}
总结
使用@synthesize,有几点需要注意:
1)如果直接写1个@synthesize
例如:@synthesize name;
那么,它自动生成一个私有属性,并且操作的是自动生成的私有属性
2)如果指定操作的属性
例如:@synthesize name = _name;
那么,它就不会自动生成私有属性,并且操作的是我们指定的带下划线的属性;
3)生成的setter方法实现当中,是没有做任何逻辑验证的,是直接赋值。如果要实现逻辑验证,需要自己写setter方法的实现。例如:
- (void)setAge:(int)age
{
if(age >= 0 && age <= 120)
{
_age = age;
}
else
_age = 18;
}
4)批量声明
例如:
@property float height , weight;
如果多个@property的类型是一致的,可以批量声明;
@synthesize name, age, weight, height;
@synthesize name = _name,age=_age,weight=_weight,height= _height;
@synthesize类型不一致,也是可以批量声明的。
边栏推荐
- wps excel 插入公式 整列
- 2022-08-01 第五小组 顾祥全 学习笔记 day25-枚举与泛型
- C陷阱与缺陷 第5章 库函数 5.5 库函数signal
- C Expert Programming Chapter 1 C: Through the Fog of Time and Space 1.4 K&R C
- C陷阱与缺陷 第7章 可移植性缺陷 7.8 随机数的大小
- CS-NP白蛋白包覆壳聚糖纳米颗粒/人血清白蛋白-磷酸钙纳米颗粒无机复合材料
- Day016 类和对象
- win10版本1803无法升级1903系统如何解决
- Interview Blitz 70: What are sticky packs and half packs?How to deal with it?
- 图的邻接矩阵存储
猜你喜欢
随机推荐
Pytorch框架学习记录8——最大池化的使用
和我一起写一个音乐播放器,听一首最伟大的作品
Appendix A printf, varargs and stdarg A.1 printf family of functions
图的邻接矩阵存储
C Expert Programming Chapter 1 C: Through the Fog of Time and Space 1.5 ANSI C Today
C陷阱与缺陷 第5章 库函数 5.5 库函数signal
Nacos 配置中心
方舟开服需要知道的那些事
写给刚进互联网圈子的人,不管你是开发,测试,产品,运维都适用
封装一个管理 url 状态的 hook
如何让定时器在页面最小化的时候不执行?
C陷阱与缺陷 第7章 可移植性缺陷 7.7 除法运算时发生的截断
2022牛客多校联赛第五场 题解
Hiking, cured my mental internal friction
空间数据库开源路,超图+openGauss风起禹贡
方舟:生存进化官服和私服区别
C Pitfalls and Defects Chapter 7 Portability Defects 7.8 Size of Random Numbers
30+的女性测试人面试经验分享
C专家编程 第1章 C:穿越时空的迷雾 1.5 今日之ANSI C
一个关于操作数据库的建议—用户密码