OC循环渐进:协议

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循环渐进:模拟实现多继承的两种方式中的【协议模拟多继承】。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值