实例变量默认只允许被当前类的对象方法来访问. 在 OC 中, 基于面向对象讨论封装是指为实例变量进行封装. 而在实际讨论封装性时, 概念会更加宽泛一些.
例如现在有一个"射击"的例子. 有一个抢的类(Gun), 里面提供子弹的个数的成员变量
提供一个射击的方法, 每次射击子弹会减少
1, 新建一个项目, 添加 Gun 类的具体实现
@interface Gun : NSObject {
@public
int _bulletCount;
}
- (void)shoot;
@end
@implementation Gun
- (void)shoot {
_bulletCount--;
NSLog(@"buibuibui... 还剩 %d 发子弹", _bulletCount);
}
@end
2, 添加 main 函数代码
int main(int argc, const char * argv[]) {
@autoreleasepool {
Gun *gun = [Gun new];
gun->_bulletCount = 3;
[gun shoot];
[gun shoot];
[gun shoot];
[gun shoot];
[gun shoot];
}
return 0;
}
3, 最后得到结论
这里不合理. 子弹需要被约束, 另外也不能初始化负数. 因此提供方法 setBulletCount
修改 Gun 类中的代码
@interface Gun : NSObject {
@public
int _bulletCount;
}
- (void)shoot;
- (void)setBulletCount:(int)count;
@end
@implementation Gun
- (void)shoot {
if (_bulletCount > 0) {
_bulletCount--;
NSLog(@"buibuibui... 还剩 %d 发子弹", _bulletCount);
} else {
NSLog(@"没有子弹...");
}
}
- (void)setBulletCount:(int)count {
if (count > 0) {
_bulletCount = count;
}
}
@end
main 函数中的使用也需要调整
int main(int argc, const char * argv[]) {
@autoreleasepool {
Gun *gun = [Gun new];
[gun setBulletCount:3];
[gun shoot];
[gun shoot];
[gun shoot];
[gun shoot];
[gun shoot];
}
return 0;
}
1, 所谓的封装
在 OC 中进行封装, 就是实现设置实例变量和获取实例变量数据的方法, 常常称为 setter 方法和 getter 方法.
2, setter 方法
setter 方法又叫设置器, 是为实例变量对外提供的统一访问规则, 用于设置实例变量的值. 一般在开发中, 禁止将实例变量直接暴露到外面. 通过 setter 方法可以为赋值操作进行必要的控制与筛选. 起到了封装和控制的作用.
规则:
1)方法名必须以 set 开头, 然后跟上实例变量的名字(无下划线)
2)使用骆驼命名规则
3) 接收一个参数, 用于为实例变量初始化
4)返回 void 类型
5)setter 是实例方法
3, getter 方法
getter 方法又叫读取器, 是用来在外访问成员变量的统一方法.
规则:
1)getter 返回与相关成员变量一致的类型数据
2)getter 没有参数
3)getter 方法的名字需要与实例变量名同名(无下划线)