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