您的位置:首页 > 职场人生

黑马程序员——OC基础---类方法的总结

2015-10-08 15:06 495 查看
------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------

1>>方法定义

+ (void) abc:(int) a andOther:(float)b;

其中‘+’为方法类型,不可省,表示这是一个类方法,区别于‘-’表示对象方法。

(void)为方法返回类型,不可省。

abc: andOther:为方法名,注意方法名包括冒号(冒号不可省),其中‘andOther’为对后一个参数的简要说明,可省(为了提高程序可读性,原则上不省略),‘andOther’与前一个参数之间必须有空格

(int)a 和 (float)b为方法的参数,如果方法不需要参数,则可省。

注意,1)每个冒号对应一个参数,如果没有参数,就不需要冒号,有一个参数,就需要一个冒号。

2)类方法名可以和对象方法名完全重名,通过‘+’‘-’来区别到底是类方法还是对象方法

-(void) abc:(int) a andOther:(float)b;

2>>方法的调用

类方法能并且只能被类调用 [类名 类方法名];

给对象发送类方法消息不会被执行,但是对象方法可以调用类方法(不限于本类,也可以是其他类的类方法),格式仍然是在对象方法中用类名调用类方法 [类名 类方法名];

类方法也同样可以调用对象方法(不限于本类,也可以是其他类),此时需要传入一个对象参数,然后用对象参数调用对象方法 [对象 对象方法名];

注意:在类方法中用self调用对象方法是错误的 [self 对象方法];

在对方法中用self调用类方法也是错误的 [self 类方法];

类方法不可以调用自身,会造成死循环。

Solider.h

#import <Foundation/Foundation.h>
@class Gun;
@class Bullet;
@interface Solider : NSObject
@property(nonatomic,copy)NSString *name;
@property(nonatomic,strong)Gun *gun;
-(void)run;
+(void)dun:(Solider*)solider;
-(void)tiao;
-(void)fff:(int )a :(float)b :(char)c;//对象方法可以与下面的类方法同名,唯独用‘+’‘-’来标记不同
+(void)fff:(int )a :(float)b :(char)c;
-(void)fire:(Solider *)soldier andGun:(Gun*) gun andBullet:(Bullet* )bullet;
@end
注意:-(void)fff:(int )a :(float)b :(char)c;与+(void)fff:(int )a :(float)b :(char)c;仅为验证可以同名定义,并未在Solider.m中实现

Solider.m

#import "Solider.h"
#import "Gun.h"
@implementation Solider
-(void)run{

NSLog(@"士兵在跑");
}
+(void)dun:(Solider*)solider{

[Gun shooot];
[solider tiao];//类方法中通过传入的对象名调用对象方法
//    [self run];//在类方法中用  self调用对象方法会报错
}
-(void)tiao{

NSLog(@"士兵跳了起来");
}
-(void)fire:(Solider *)soldier andGun:(Gun*) gun andBullet:(Bullet* )bullet{

[soldier run];
[Solider dun:soldier];//对象方法中用类名调用了类方法
//    [self dun];//对象方法中用  self调用类方法会报错
[gun shoot:bullet andSoldier:self];
}
@end


Gun.h

#import <Foundation/Foundation.h>
@class Bullet;
@class Solider;
@interface Gun : NSObject
@property(nonatomic,copy)NSString *size;
-(void)shoot:(Bullet *)bullet andSoldier:(Solider *) solider;
+(void)shooot;
@end


Gum.m

#import "Gun.h"
#import "Bullet.h"
#import "Solider.h"
@implementation Gun
-(void)shoot:(Bullet *)bullet andSoldier:(Solider *) solider{

if ([bullet bulletCount]>0) {
[bullet setBulletCount:[bullet bulletCount]-1];
NSLog(@"啪啪啪。。。%@用%@在射击。。。当前子弹剩余%d", [solider name],[self size],[bullet bulletCount]);
}else
{
NSLog(@"没有子弹了,赶紧内裤挂枪投降吧!");
}
}

+(void)shooot{

NSLog(@"shooot");
}
@end


Bullet.h

#import <Foundation/Foundation.h>

@interface Bullet : NSObject
@property(nonatomic,assign)int bulletCount;
@end


Bullet.m

#import "Bullet.h"

@implementation Bullet

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: