OC語言day07-01協議基本概念

pragma mark 協議基本概念

pragma mark 概念

/**
 1.protocol基本概念
 > Protocol 叫做"協議"

 >Protocol作用
 用來聲明一些方法
 也就是說,一個Protocol是有一系列的方法聲明組成的
 
 2.protocol 語法格式
 > Protocol的定義
 
 @protocol 協議名稱
 // 方法聲明列表
 @end
 
 > 類遵循協議
    一個類 可以遵守1個或者多個協議
    任何類 只要遵守了Protocol, 就相當于擁有了 Protocol的所有方法聲明
 
 @interface 類名 : 父類 <協議名稱>
 @end
 
3.protocol和繼承的區別
 繼承之后 默認就有了實現, 而protocol只和聲明沒有實現
 相同類型的類 可以使用 繼承, 但是不同的類型只能使用protocol
 protocol 可以用于 存儲方法的聲明,  可以將多個類中共同的方法抽取出來,以后這些開發遵守協議即可
 */

pragma mark 代碼

#import <Foundation/Foundation.h>
#pragma mark 類
#import "Person.h"
#import "Student.h"
#import "Teacher.h"
#pragma mark main函數
int main(int argc, const char * argv[])
{
    Person *p = [[Person alloc]init];
    [p playFootball];
    [p playBasketBall];
    [p playBaseBall];
    
    Student *s = [[Student alloc]init];
    [s playFootball];
    
    Teacher *t = [[Teacher alloc]init];
    [t playFootball];
    
    return 0;
}


Person.h //人類
#import <Foundation/Foundation.h>
#import "SportProtocol.h"
@interface Person : NSObject <SportProtocol>

//- (void)playFootball;
@end
Person.m
#import "Person.h"

@implementation Person
- (void)playFootball
{
    NSLog(@"%s",__func__);
}

-(void)playBaseBall
{
    NSLog(@"%s",__func__);
}

-(void)playBasketBall
{
    NSLog(@"%s",__func__);

}
@end

Student.h //學生類
#import <Foundation/Foundation.h>
#import "SportProtocol.h"
@interface Person : NSObject <SportProtocol>

//- (void)playFootball;
@end
Student.m
@implementation Student
- (void)playFootball
{
    NSLog(@"s %s",__func__);
}

-(void)playBaseBall
{
    NSLog(@"s %s",__func__);
}

-(void)playBasketBall
{
    NSLog(@"s %s",__func__);
    
}
@end

Teacher.h // 教師類
#import <Foundation/Foundation.h>
#import "SportProtocol.h"
@interface Teacher : NSObject <SportProtocol>

@end
Teacher.m
#import "Teacher.h"

@implementation Teacher

- (void)playFootball
{
    NSLog(@"t %s",__func__);
}

-(void)playBaseBall
{
    NSLog(@"t %s",__func__);
}

-(void)playBasketBall
{
    NSLog(@"t %s",__func__);
    
}

@end

Dog.h //狗類
#import <Foundation/Foundation.h>
#import "SportProtocol.h"
@interface Dog : NSObject<SportProtocol>

@end
Dog.m
#import "Dog.h"

@implementation Dog
- (void)playFootball
{
    NSLog(@"d %s",__func__);
}

-(void)playBaseBall
{
    NSLog(@"d %s",__func__);
}

-(void)playBasketBall
{
    NSLog(@"d %s",__func__);
    
}
@end

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容