行业知识
OC-协议
2026-11-30 14:09:43
来源:互联网转载
什么是协议
定义一���方法 由其他类来实现。
()如果一个类实现了这个协议则代表这个类遵循了这个协议
格式
@protocol 协议的名字 // 一般情况下 父协议是NSObject
创建协议
//Pro.h@protocol pro -(void)play;//并不在Son的头文件中声明 而是在协议中声明这个方法@optional//标识下面这个函数可实现 也可以不实现-(void)read;@required//标识下面这个函数必须实现 默认就是required-(void)eat;@end
导入协议
//Son.himport"Pro.h"@interface Son:NSObject//-(void)play//不声明@end//Son.mimport"Son.h"@implementation Son-(void)play{NSLog(@"%@",__func__)}@end//main.mimport"Foundation/Foundation.h"import"Son.h"int main(){ Son *s = [[Son alloc]init]; [s play];//发现也能调用} 协议限制传入的参数 也可以限制成员变量
创建协议
()//people.h 创建一个人的协议@protocol people -(char*)name;-(id)initWithName;@end
创建女人类
//Woman.himport"people.h"@interface Woman:NSObject{char *_name;id friend;//可以改成下面这样}//@property idfriend;//直接限制成员变量-(void)setWithFriend:(id)f@end//Woman.mimport"Woman.h"@implementation Woman-(void)setWithFriend:(id)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.himport"people.h"@interface Man:NSObject{char *_name;id *friend;}@end//Man.mimport"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.mimport"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)];