码迷,mamicode.com
首页 > 其他好文 > 详细

【非凡程序员】 OC第十一节课 (协议)

时间:2015-06-02 00:35:34      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

 

//协议特点:制定一份协议,其他类如果遵守就需要去实现前提是required(默认)
// < > 遵守
// NSObject 既是基协议 又是基类,因此,协议最终都需遵守NSObject
// required 必须实现  optional 可选实现
// respondToSelector:@selector(方法名) 判断一个方法是否存在
// 子类继承父类 那么子类也遵守父类的协议
// 协议可以多遵守,如: <myProtocol , NSObject>
// 警记! 协议只是类似方法声明,实现还在自己类中
// 类与类之间相互引用 @class 前置一个。
// 对象与对象之间相互调用 至少一端是weak。


#import <Foundation/Foundation.h>

//定义一个协议 名字是myProtocol 遵守基协议 <NSObject>
@protocol myProtocol <NSObject>

 

//必须实现的
@required

- ( void ) say;
@property(nonatomic, strong) NSTimer *timer;
@property(nonatomic, assign) int timerCount;

//可选实现的
@optional

- ( void ) log;
@end

//Person的另一个协议teach
@protocol teach <NSObject>
//可选的
@optional
- (void) run;
- (void) speak;
- (void) teach:(NSString *)sentence;

@end

 

//判断是否存在say方法(重点)

   SEL sel = @selector(say);
        if( [person1 respondsToSelector:sel ]){
            NSLog( @" you  say  " );
        }else{
            NSLog( @" meiyou  say " );
        }
       

//子类一旦继承父类,相关父类遵守的协议 子类也需要遵守 可以使用
@interface Student : Person

@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];

 

 

【非凡程序员】 OC第十一节课 (协议)

标签:

原文地址:http://my.oschina.net/u/2366900/blog/423649

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!