Objective-c有一条便捷途径,可以简化存取方法的过程。该途径称为属性。
通过属性可以简化代码。
目录
一、声明属性
在BNRPerson.h中删除实例变量,然后用下面两个属性heightInMeters和weightInKilos重写存取方法的声明。
@interface BNRPerson : NSObject
//BNRPerson类有两个属性
@property (nonatomic) float heightInMeters;
@property (nonatomic) int weightInKilos;
//{
// //BNRPerson类拥有两个实例变量
// float _heightInMeters; //身高
// int _weightInKilos; //体重
//}
……
@end
属性的声明以@property开始 。
声明属性的时候,编译器不仅会帮你声明存取方法,还会根据属性的声明实现存取方法。
也就是说,在BNRPerson.m中不需要再写存取方法了,因为我们已经声明了属性,直接使用编译器生成好的存取方法就可以了,于是BNRPerson.m变成了如下的样子。
@implementation BNRPerson
//BNRPerson类拥有计算Body Mass Index的方法
-(float) bodyMassIndex
{
float h = [self heightInMeters];
return [self weightInKilos] / (h * h);
}
@end
二、属性的特性
属性的声明可以有一个或多个属性特性。
默认属性不需要在声明中设置。
非原子性:nonatomic
原子性:atomic,默认值
属性要么是原子性要么是非原子性。区别和多线程运行有关。
只读性:readonly
读写属性:readwrite,默认值
可拷贝性:copy,每当声明一个指向NSString或NSArray对象的属性时,都需要设置copy属性。
三、用逗号调用存取方法
修改main.m中的文件:
#import <Foundation/Foundation.h>
#import "BNRPerson.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
BNRPerson* mikey = [[BNRPerson alloc] init];
//使用存方法给实例变量赋值
mikey.heightInMeters = 1.62;
mikey.weightInKilos = 46;
//使用取方法打印实例变量的值
float height = mikey.heightInMeters;
int weight = mikey.weightInKilos;
NSLog(@"mikey is %.2f meters tall and weights %d kilos", height, weight);
//使用定制的方法打印相应的BMI的值
float bmi = [mikey bodyMassIndex];
NSLog(@"mikey has a BMI of %.2f", bmi);
}
return 0;
}
使用点号调用存取方法的时候实际上是在发送消息。
根据使用情况,可能发送一条至两条消息。
也就是根据是否读取,调用相应的取方法或存方法。
三、BNRPerson完整代码
.h文件
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface BNRPerson : NSObject
//BNRPerson类有两个属性
@property (nonatomic) float heightInMeters;
@property (nonatomic) int weightInKilos;
//{
// //BNRPerson类拥有两个实例变量
// float _heightInMeters; //身高
// int _weightInKilos; //体重
//}
//BNRPerson类声明实例方法
-(float) heightInMeters;
-(void) setHeightInMeters:(float) h;
-(int) weightInKilos;
-(void) setWeightInKilos:(int) w;
//BNRPerson类拥有计算Body Mass Index的方法
-(float) bodyMassIndex;
@end
NS_ASSUME_NONNULL_END
.m文件
#import "BNRPerson.h"
@implementation BNRPerson
//BNRPerson类拥有计算Body Mass Index的方法
-(float) bodyMassIndex
{
float h = [self heightInMeters];
return [self weightInKilos] / (h * h);
}
@end
main.m文件
#import <Foundation/Foundation.h>
#import "BNRPerson.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
BNRPerson* mikey = [[BNRPerson alloc] init];
//使用存方法给实例变量赋值
mikey.heightInMeters = 1.62;
mikey.weightInKilos = 46;
//使用取方法打印实例变量的值
float height = mikey.heightInMeters;
int weight = mikey.weightInKilos;
NSLog(@"mikey is %.2f meters tall and weights %d kilos", height, weight);
//使用定制的方法打印相应的BMI的值
float bmi = [mikey bodyMassIndex];
NSLog(@"mikey has a BMI of %.2f", bmi);
}
return 0;
}
四、练习
本小节木有练习的,是本人附加的🙈🙈
还记得上节的股票类吗?试着把那里实例变量的存取方法声明为属性吧
给你点个赞👍