您的位置:首页 > 其它

7、协议protocol-OC

2013-12-26 20:19 162 查看
(1)什么是协议

(2)如何定义协议

(3)如何使用协议

(1)什么是协议

1、多个对象之间协商的一个接口对象。

2、提供一系列的方法来在协议的实现者和代理者之间的一种通信。

3、类似于c++中 纯虚函数,或java中的接口。

(2)如何定义协议

1、只有头文件

2、方法定义

@protocolMyprotocol <NSObject>

- (void) init;

- (int) updata:(int)time;

@end

3、协议中不是每个方法都要实现的。

@required [方法必须实现]

@optional [方法可以实现、缺省]

协议需要继承于 基协议NSObject

协议可以多继承

@protocolMyprotocol <NSObject>

@optional

- (void) init;

@required

- (int)>

一个简单协议例子

协议使用例子:

怎么知道shwoinfo这个方法是否写了。

5、判断某个对象是否响应方法

动态判断某个方法是否实现了。

if( [test respondsToSelector:@selector(showInfo:)] )

{

[test>YES; 

}

(3)如何使用协议

创建一个协议:

#import <Foundation/Foundation.h>

@protocol Myprotocol <NSObject>
@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 <Foundation/Foundation.h>
#import "Myprotocol.h"

@interface TestProtocol : NSObject <Myprotocol>
{

}

- (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 <Foundation/Foundation.h>
#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> myprotocol = [[TestProtocol alloc] init];
[myprotocol printValue:103];

[myprotocol release];
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: