pragma mark 对象作为返回值
pragma mark 概念
/**
如果方法中没有 使用到 属性(成员变量) 可以变成类方法
*/
pragma mark 代码
#import <Foundation/Foundation.h>
#pragma mark - 类
#pragma mark - 弹夹
@interface Clip : NSObject
{
@public
int _bullet; //子弹
}
// 上子弹的方法
- (void)addBullet;
@end
@implementation Clip
- (void)addBullet
{
// 上子弹
_bullet = 10;
}
@end
#pragma mark - 枪
@interface Gun : NSObject
{
//@public
// int _bullet; //子弹
Clip *clip; // 弹夹
}
// 射击的方法
//- (void)shoot;
// 注意: 在企业级开发中 千万不要随意修改一个方法
- (void)shoot;
// 想要射击 必须传递一个弹夹
- (void)shoot:(Clip *)c;
@end
@implementation Gun
//- (void)shoot
//{
// if (_bullet > 0) {
// _bullet --;
// NSLog(@"打了一枪 还剩余%d发",_bullet);
// }
// else
// {
// NSLog(@"没有子弹了,请换弹夹");
// }
//}
- (void)shoot:(Clip *)c
{
// 判断有没有弹夹
if(c != nil) // nil == null == 没有值
{
// 判断有没有子弹
if (c->_bullet >0)
{
c->_bullet -= 1;// 子弹减1
NSLog(@"打了一枪 还剩余%d发",c->_bullet);
}
else
{
NSLog(@"没有子弹了");
[c addBullet];
}
}
else
{
NSLog(@"没有弹夹,请换弹夹");
}
}
@end
#pragma mark - 士兵
@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 *)gun
{
[gun shoot];
}
// Gun * g = gun
- (void)fire:(Gun *)g clip:(Clip *)clip
{
// 判断 是否有枪和子弹
if (g != nil && clip != nil) {
[g shoot:clip];
}
}
@end
@interface Shop : NSObject
#warning 如果方法中没有 使用到 属性(成员变量) 可以变成类方法
//// 买枪方法
//- (Gun *)buyGun:(int)monery;
//// 买弹夹方法
//- (Clip *)buyClip:(int)monery;
// 买枪方法
+ (Gun *)buyGun:(int)monery;
// 买弹夹方法
+ (Clip *)buyClip:(int)monery;
@end
@implementation Shop
#warning 如果方法中没有 使用到 属性(成员变量) 可以变成类方法
//// 买枪方法
//- (Gun *)buyGun:(int)monery
//{
// // 1.创建一把枪
// Gun *gun = [Gun new]; // 通过new创建 出来的对象 存储在堆中,堆中的数据 不会自动释放
// return gun;
//}
//// 买弹夹方法
//- (Clip *)buyClip:(int)monery
//{
// Clip *clip = [Clip new];
// [clip addBullet];// 买弹夹 给他加点子弹
// return clip;
//}
// 买枪方法
+ (Gun *)buyGun:(int)monery
{
// 1.创建一把枪
Gun *gun = [Gun new]; // 通过new创建 出来的对象 存储在堆中,堆中的数据 不会自动释放
return gun;
}
// 买弹夹方法
+ (Clip *)buyClip:(int)monery
{
Clip *clip = [Clip new];
[clip addBullet];// 买弹夹 给他加点子弹
return clip;
}
@end
int main(int argc, const char * argv[])
{
// 1.创建士兵
Soldier *sp = [Soldier new];
sp->_name = @"狗蛋";
sp->_height = 1.92;
sp->_weight = 88.0;
// 2.商家对象
#warning 类方法 不需要创建对象了
// Shop *shop = [Shop new];
/*
// 2.创建一把枪
// Gun *gun = [Gun new];
// gun->_bullet = 10;
// 3.创建弹夹
// Clip *clip = [Clip new];
// [clip addBullet];// 添加子弹
*/
// 3.购买枪
Gun *gp = [Shop buyGun:888];
// 4.购买弹夹
Clip *clip = [Shop buyClip:100];
#warning 士兵 拿到 枪 和 弹夹 就可以开火了
// 4.让士兵开枪
// [sp fire];
[sp fire:gp clip:clip];
#warning 让对象作为函数的参数传递
return 0;
}