协议文件
//协议 @protocol IOSBase -(void)knowc; -(void)knowoc; -(void)canDevelopiOS; @end
@protocol IOSBaseplus @optional//可选的 -(void)knowcpower; @required//必须的 默认都是必须的 -(void)knowocpower; -(void)canDevelopiOSpower; @end
协议文件的使用
.h
#import <Foundation/Foundation.h> #import "person.h" #import "iosbase.h" #import "iosAdvance.h" NS_ASSUME_NONNULL_BEGIN @interface IOSProgrammer : person <IOSBase,IOSBaseplus> @property int year1; @property int year2; @property int num; @property int year3; @property int year4; @property int num2; @end
.m
#import "IOSProgrammer.h" @implementation IOSProgrammer -(void)knowc { NSLog(@"%i年c语言开发经验",_year1); } -(void)knowoc { NSLog(@"%i开发经验",_year2); } -(void)canDevelopiOS { NSLog(@"开发过%i个小程序",_num); } -(void)knowcpower { NSLog(@"%i年c语言高级开发经验",_year3); } @end
.main
int main(int argc, const char * argv[]) { @autoreleasepool { // insert code here... NSLog(@"Hello, World!"); IOSProgrammer* p1=[[IOSProgrammer alloc] initWithName:@"zhangsan" andAge:25 andGender:'m']; [p1 setYear1:1]; [p1 setYear2:2]; [p1 setNum:3]; [p1 setYear3:3]; [p1 knowcpower]; // [p1 show]; // [p1 knowoc]; // [p1 knowc]; // [p1 canDevelopiOS]; IOSProgrammer* p2=[[IOSProgrammer alloc] initWithName:@"lisi" andAge:30 andGender:'m']; [p2 setYear1:2]; [p2 setYear2:4]; [p2 setNum:6]; person* p3=[[person alloc] initWithName:@"wanger" andAge:25 andGender:'m']; NSArray *array=@[p1,p2,p3]; for(id p in array) // 检查是否遵守协议 {if([p conformsToProtocol:@protocol(IOSBase)]) if([p year1]>1) { [p show]; [p knowoc]; [p knowc]; } }