什么是协议
定义一组方法 由其他类来实现。
如果一个类实现了这个协议则代表这个类遵循了这个协议
格式
@protocol 协议的名字<父协议> // 一般情况下 父协议是NSObject
创建协议
//Pro.h
@protocol pro<NSObject>
-(void)play;//并不在Son的头文件中声明 而是在协议中声明这个方法
@optional//标识下面这个函数可实现 也可以不实现
-(void)read;
@required//标识下面这个函数必须实现 默认就是required
-(void)eat;
@end
导入协议
//Son.h
import"Pro.h"
@interface Son:NSObject<pro/*,这里可以添加其他的协议*/>
//-(void)play//不声明
@end
//Son.m
import"Son.h"
@implementation Son
-(void)play
{
NSLog(@"%@",__func__)
}
@end
//main.m
import"Foundation/Foundation.h"
import"Son.h"
int main()
{
Son *s = [[Son alloc]init];
[s play];//发现也能调用
}
协议限制传入的参数 也可以限制成员变量
创建协议
//people.h 创建一个人的协议
@protocol people<NSObject>
-(char*)name;
-(id)initWithName;
@end
创建女人类
//Woman.h
import"people.h"
@interface Woman:NSObject<people>
{
char *_name;
id friend;//可以改成下面这样
}
//@property id<people>friend;//直接限制成员变量
-(void)setWithFriend:(id)<people>f
@end
//Woman.m
import"Woman.h"
@implementation Woman
-(void)setWithFriend:(id)<people>f//只允许与遵守人协议的对象做朋友
{
NSLog(@"%@:%@",__func__,[f name]);
}
-(id)initWithName:(char*)n;
{
if((self = [[super alloc]init])!= nil)
{
_name = n;
}
return self;
}
-(char*)name
{
return name;
}
@end
创建男人类
//Man.h
import"people.h"
@interface Man:NSObject<people>
{
char *_name;
id *friend;
}
@end
//Man.m
import"Man.h"
@implementation Man
-(id)initWithName:(char*)n;
{
if((self = [[super alloc]init])!= nil)
{
_name = n;
}
return self;
}
-(char*)name
{
return name;
}
@end
创建狗类
//Dog.h
@interface Dog:NSObject
@end
//Dog.m
import"Dog.h"
@implementation Dog
@end
main
int main()
{
Woman *hong = [[Woman alloc]initWithName:@"小红"];
Man*ming = [[Man alloc]initWithName:@"小明"];
Dog*huang = [[Dog alloc]init];
[hong setWithFriend:ming];//setWithFriend:小明
//[hong setWithFriend:huang];//这样就会报错 因为dog不遵守人的协议
}
BOOL conformsToProtocol: 判断是否遵循协议
[hong conformsToProtocol:@protocol(people)];