美文网首页八天学会OC
第02天OC语言(09):对象作为方法的参数连续传递下

第02天OC语言(09):对象作为方法的参数连续传递下

作者: liyuhong | 来源:发表于2017-07-20 14:54 被阅读14次
一、概念
二、代码
#import <Foundation/Foundation.h>
#pragma mark 类
#pragma mark - 3.弹夹

@interface Clip : NSObject
{
@public
    int _bullet;
}
- (void)addBullet;
@end

@implementation Clip
- (void)addBullet
{
    // 上子弹
    _bullet = 10;
}
@end

#pragma mark - 2.枪
@interface Gun : NSObject
{
@public
    Clip *clip; // 弹夹
    
}
// 注意 : 在企业开发中 千万不要随意修改一个方法
- (void)shoot;
// 想要射击,必须传递弹夹
- (void)shoot:(Clip *)c;

@end

@implementation Gun

- (void)shoot:(Clip *)c
{
    
    if (c != nil) { // nul == null == 没有值
        // 判断有没有子弹
        if (c->_bullet > 0) {
            c->_bullet -=1;
            NSLog(@"打了一枪 %i",c->_bullet);
        }
        else
        {
            NSLog(@"没有子弹了");
        }
    }
    else
    {
        NSLog(@"没有弹夹 ,请换弹夹");
    }
}
@end
#pragma mark - 1.士兵
@interface Soldier : NSObject
{
@public
    NSString *_name;
    double _height;
    double _weight;
}
- (void)fire:(Gun *)gun;
// 开火,给士兵 一把枪,和弹夹
- (void)fire:(Gun *)g Clip:(Clip *)clip;
@end

@implementation Soldier

- (void)fire:(Gun *)g
{
    [g shoot];
}

- (void)fire:(Gun *)g Clip:(Clip *)clip
{
    // 判断是否 有枪 和子弹
    if (g != nil &&
        clip != nil) // 这里我觉得不用判断 clip是不是为空,因为我在shoot里面已经判断了,如果没有的话 就提示更换弹夹
    {
        [g shoot:clip];
    }
}
@end

#pragma mark - main函数
int main(int argc, const char * argv[])
{
    // 1.创建士兵
    Soldier *s = [Soldier new];
    s->_name = @"lyh";
    s->_height = 1.71;
    s->_weight = 65.0;
    
    // 2.创建枪
    Gun *gp = [Gun new];
    
    // 3.创建弹夹
    Clip *clip = [Clip new];
    [clip addBullet];
    
    // 4.士兵开火
    [s fire:gp Clip:clip];
    
    
    return 0;
}
image.png

相关文章

网友评论

    本文标题:第02天OC语言(09):对象作为方法的参数连续传递下

    本文链接:https://www.haomeiwen.com/subject/twcphxtx.html