7、协议protocol-OC

本文深入探讨了Objective-C中的协议概念,包括协议的定义、使用方法以及如何判断方法是否被实现,通过实例展示了协议在实际开发中的应用。

(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;
}















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值