三大特性之封装

 

main.m

#import <Foundation/Foundation.h>
#import "Gun.h" //使用某个类先引入该类的类声明

int main(int argc, const char * argv[]) {
//    1、没有封装的情况下
//    Gun *pg = [Gun new];
//    pg->_bullet = -3; // 子弹怎么能赋值为负数呢?脏数据
//    [pg shoot];
    
//    2、使用了get/set进行封装之后
    Gun *pg = [Gun new];
    [pg setBullet:-3];
    
    return 0;
}

Gun.h

#import <Foundation/Foundation.h>

@interface Gun : NSObject
{
//    @public 使用了get/set进行封装之后
    int _bullet;
}
- (void)setBullet:(int)bullet;
- (int)bullet;

- (void)shoot;
@end

Gun.m

#import "Gun.h"

@implementation Gun
- (void)setBullet:(int)bullet{
    if (bullet<0) {
        NSLog(@"子弹不能为负数"); // 对脏数据进行过滤
    }else{
        _bullet=bullet;//这就是为什么要将成员变量定义成 _bullet的形式的原因之一
    }
}
- (int)bullet{
    return _bullet;
}

- (void)shoot{
    NSLog(@"射击了一次,还剩%i个子弹",--_bullet);
}
@end

 

posted @ 2016-06-16 11:00  Shaper22  阅读(153)  评论(0编辑  收藏  举报