(1)什么是协议
(2)如何定义协议
(3)如何使用协议
(1)什么是协议
1、多个对象之间协商的一个接口对象。
2、提供一系列的方法来在协议的实现者和代理者之间的一种通信。
3、类似于c++中 纯虚函数,或java中的接口。
(2)如何定义协议
1、只有头文件
2、方法定义
@protocolMyprotocol
- (void) init;
- (int) updata:(int)time;
@end
3、协议中不是每个方法都要实现的。
@required [方法必须实现]
@optional [方法可以实现、缺省]
协议需要继承于 基协议NSObject
协议可以多继承
@protocolMyprotocol
@optional
- (void) init;
@required
- (int)>
一个简单协议例子
![\]()
协议使用例子:
![]()
怎么知道shwoinfo这个方法是否写了。
5、判断某个对象是否响应方法
动态判断某个方法是否实现了。
if( [test respondsToSelector:@selector(showInfo:)] )
{
[test>YES;
}
(3)如何使用协议
创建一个协议:
#import
@protocol Myprotocol
@optional - (void) printValue:(int)value; @required - (int) printValue:(int)value1 andValue:(int)Value2; @end
实现协议的方法:
//
// TestProtocol.h
// TestPortocal
//
// Created by ccy on 13-12-21.
// Copyright (c) 2013年 ccy. All rights reserved.
//
#import
#import "Myprotocol.h"
@interface TestProtocol : NSObject
{ } - (void) testValue:(int) Value; @end
//
// TestProtocol.m
// TestPortocal
//
// Created by ccy on 13-12-21.
// Copyright (c) 2013年 ccy. All rights reserved.
//
#import "TestProtocol.h"
@implementation TestProtocol
- (void) testValue:(int) Value
{
NSLog(@"testValue value: %d\n", Value);
}
- (int) printValue:(int)value1 andValue:(int)Value2
{
NSLog(@"printValue value1: %d,value2:%d\n", value1,Value2);
return 0;
}
- (void) printValue:(int)value
{
NSLog(@"printValue %d\n", value);
}
@end
调用,使用协议:
//
// main.m
// TestPortocal
//
// Created by ccy on 13-12-21.
// Copyright (c) 2013年 ccy. All rights reserved.
//
#import
#import "TestProtocol.h"
//#import "Myprotocol.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
TestProtocol * testPtcl = [[TestProtocol alloc] init];
[testPtcl testValue:2];
[testPtcl printValue:30 andValue:40];
//判断方法有没有实现
SEL sel = @selector(printValue:);
if( [testPtcl respondsToSelector:sel])
{
[testPtcl printValue:20];
}
[testPtcl release];
//用协议方式实现
id
myprotocol = [[TestProtocol alloc] init]; [myprotocol printValue:103]; [myprotocol release]; } return 0; }