协议就是定义一组方法实现类必须实现这些方法,类似于java的接口和抽象类
协议的定义语法:
@protocol 协议名 <父协议>
定义方法
@end
注:定义协议的关键字是@protocol,同时协议也是可以继承父协议的
协议中定义的方法还有两个修饰符:
@required:这个表示这个方法是其他类必须实现的,也是默认的值
@optional:这个表示这个方法对于其他类实现是可选的
协议的定义TestProtocol.h
//oc协议的简单使用
@protocol TestProtocol <NSObject>
@required//必须实现
-(void)printlf;
+(void)getHotel;
@optional//可选实现
-(void)setHotel;
@end
#endif /* TestProtocol_h */
文件TestExtends.h
#import "TestProtocol.h" @interface TestExtends: NSObject<TestProtocol>{ NSString* name; } @property NSString *name; //类似set和get方法 //@property name; -(void)setName:(NSString*)newName;//定义方法 -(id)initWithC:(NSString*)newName;//定义构造方法 @end #endif /* TestExtends_h */
TestExtends.m文件
#import "TestExtends.h"
@implementation TestExtends
@synthesize name;
-(void)setName:(NSString*)newName{
NSLog(@"调用父类的setName方法");
}
+(void)getHotel{
NSLog(@"getHotel");//必须实现的方法
}
-(void)printlf{
NSLog(@"printlf");//必须实现的方法
}
-(void)setHotel{
NSLog(@"setHotel");//可选的方法
}
-(id)initWithC:(NSString *)newName{
if (self==[super init]) {
name=newName;//
NSLog(@"父类的构造方法被调用。。。。");
}
return self;
}
@end
mian文件
TestExtends* te=[[TestExtends alloc] init];
[te setName:@"Object-c"];
NSLog(@"简单的实现");
[te printlf]; //调用协议的方法
运行结果:
2015-11-04 23:04:40.179 test_01[1432:80295] 调用父类的setName方法
2015-11-04 23:04:40.180 test_01[1432:80295] 简单的实现
2015-11-04 23:04:40.180 test_01[1432:80295] printlf
(lldb)