//协议特色:制定一份协议,其余类若是遵照就须要去实现前提是required(默认)
// < > 遵照
// NSObject 既是基协议 又是基类,所以,协议最终都需遵照NSObject
// required 必须实现 optional 可选实现
// respondToSelector:@selector(方法名) 判断一个方法是否存在
// 子类继承父类 那么子类也遵照父类的协议
// 协议能够多遵照,如: <myProtocol , NSObject>
// 警记! 协议只是相似方法声明,实现还在本身类中
// 类与类之间相互引用 @class 前置一个。
// 对象与对象之间相互调用 至少一端是weak。函数
#import <Foundation/Foundation.h>oop
//定义一个协议 名字是myProtocol 遵照基协议 <NSObject>
@protocol myProtocol <NSObject>ui
//必须实现的
@required
- ( void ) say;
@property(nonatomic, strong) NSTimer *timer;
@property(nonatomic, assign) int timerCount;atom
//可选实现的
@optional
- ( void ) log;
@endspa
//Person的另外一个协议teach
@protocol teach <NSObject>
//可选的
@optional
- (void) run;
- (void) speak;
- (void) teach:(NSString *)sentence;.net
@end对象
//判断是否存在say方法(重点)继承
SEL sel = @selector(say);
if( [person1 respondsToSelector:sel ]){
NSLog( @" you say " );
}else{
NSLog( @" meiyou say " );
}
get
//子类一旦继承父类,相关父类遵照的协议 子类也须要遵照 能够使用
@interface Student : Personit
@end
//标准协议写法 须要写出所遵照的协议
Student<teach> *stu = [[Student alloc]init];
//当类属性写在协议里是,在类中的.m文件中须要用@synthesize(重点)
@implementation Person
@synthesize timer = _timer , timerCount = _timerCount;
//如下是NSTimer的使用方法(重点)
- (id) init
{
self = [super init];
if( self ){
_timer = [NSTimer scheduledTimerWithTimeInterval:1.0F target:self selector:@selector(say) userInfo:nil repeats:YES];
}
return self;
}
- (void) say
{
_timerCount++;
NSLog( @"人说:Hello %i" , _timerCount);
if( _timerCount > 5 ){
[_timer invalidate];
}
}
@end
//main函数中写的调用函数 (重点)
//[[NSRunLoop currentRunLoop]run];