OC中的协议就相当于Java中的接口,那个类实现了这个协议就必须实现协议里面的方法。
以下为一个实例:
Student.h 的代码文件如下:
#import <Foundation/Foundation.h>
@protocol StudentProtocol <NSObject>
//必须实现的方法,不写时默认
@required
- (void)sayHi;
//可选择的方法
@optional
- (void)sayHello;
@end
@interface Student : NSObject <StudentProtocol>
@end
Student.m 的代码文件如下:
#import "Student.h"
@implementation Student
- (void)sayHi {
NSLog(@"%s",__FUNCTION__);
}
@end
main.m 的代码文件如下:
#import <Foundation/Foundation.h>
#import "Student.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Student *stu = [[Student alloc] init];
[stu sayHi];
}
return 0;
}
测试结果如下:
2015-08-10 13:46:52.985 Demo01[17201:125120] -[Student sayHi]
当然,协议里也不能定义属性,当可以使用@property声明setter和getter方法,详情请参考我的OC循环渐进:类目和延展中的【模拟延展属性】和OC循环渐进:模拟实现多继承的两种方式中的【协议模拟多继承】。
363

被折叠的 条评论
为什么被折叠?



