【使用Property创建存取器】
来源:互联网 发布:嘉兴 行李箱 知乎 编辑:程序博客网 时间:2024/06/10 23:39
使⽤用
@Property
创建存取器
使⽤用
@Property
创建存取器
// Car.h#import <Foundation/Foundation.h>@interface Car : NSObject{// 实例变量NSString *carName;
NSString *carType;
}@property(nonatomic,strong) NSString *carName;
@property(nonatomic,strong) NSString *carType;
@end
(让我们先忽略nonatomic和strong)。
// Car.m#import "Car.h"
@implementation Car
@synthesize carName;
@synthesize carType;
@end
在.m⽂文件中我们使⽤用@synthesize⾃自动⽣生成这两个实例变量的存取器,并且隐藏了存取器,虽然我们看不到存取器,但它们确实是存在的。
// main.mint main(int argc, char * argv[]){ @autoreleasepool { Car *car = [[Car alloc] init];
car.carName = @"Jeep Compass";
car.carType = @"SUV"; NSLog(@"The car name is %@ and the type is %@",car.carName,car.carType);
} return 0;
}在上⾯面的代码中我们可以注意到,Car对象使⽤用点语法给存取器发送消息,并且get与set的语法是相同的,所以这⾥里的点语法可以根据语境判断我们是要赋值还是取值。
当然我们也依然可以使⽤用消息语法来使⽤用:
// main.mint main(int argc, char * argv[]){ @autoreleasepool { Car *car = [[Car alloc] init];// 点语法// car.carName = @"Jeep Compass";
// car.carType = @"SUV";// NSLog(@"The car name is %@ and the type is %@",car.carName,car.carType); // 消息语法 [car setCarName:@"Jeep Compass"];
[car setCarType:@"SUV"]; NSLog(@"The car name is %@ and the type is %@",[car carName],[car carType]);
} return 0;
}上⾯面两段代码的执⾏行结果都是:
The car name is Jeep Compass and the type is SUV
总结:@property等同于在.h⽂文件中声明实例变量的get/set⽅方法,@synthesize等同于在.m⽂文件中实现实例变量的get/set⽅方法。使⽤用@property和synthesize创建存取器要⽐比⼿手动声明两个存取⽅方法(getter和setter)更简单。⽽而且我们在使⽤用属性时可以使⽤用点语法赋值或取值,语法更简单,更符合⾯面向对象编程。
如果我们希望使⽤用默认的实例变量命名⽅方式,那么我们在.m⽂文件中就不需要使⽤用@synthesize声明,系统会帮我们⾃自动完成。如果我们希望⾃自⼰己命名实例变量命,那么我们就使⽤用@synthesize显⽰示声明我们希望的实例变量名。
0 0
- 【使用Property创建存取器】
- 014.@property 合成存取方法
- 014.@property 合成存取方法
- 合成存取方法 @property @synthesize
- iOS开发-OC中属性创建需要注意的地方(property实例变量的创建和标准存取方法)
- iOS开发-OC中属性创建需要注意的地方(property实例变量的创建和标准存取方法)
- 创建顺序存取文件
- 【OC学习-9】利用@property属性和@synthesize简化实例变量的存取器方法
- 使用@property
- 使用@property
- 使用@property
- 使用@property
- 使用@property
- 使用@property
- 3.2 创建与存取数组
- javaScript 创建对象 property
- 使用JDBC存取数据库
- 使用mysqli存取数据
- 欢迎使用CSDN-markdown编辑器
- 黑马-面试经历2
- JS 导出网页中Table内容到excel
- double格式小数位
- 测试测试
- 【使用Property创建存取器】
- log4j 自定义 level
- GEM5与SystemC混合仿真的实现
- poj 3264 Balanced Lineup 【RMQ 裸题】
- 【暑期基础2】N HDU 2039 三角形
- Linux下大文件分割和小文件合并
- 运营商的三大垄断性思维
- Android开发面试经——1.常见人事面试问题
- 取消京津冀手机漫游费更像文字游戏