Objective-C之protocol协议

来源:互联网 发布:电影资源采集站源码 编辑:程序博客网 时间:2024/05/16 10:48

1 前言

@protocol是Objective-C中普遍存在的接口定义方式,即在一个类中通过@protocol定义接口,在另外类中实现接口,这种接口定义方式也成为“delegation”模式,@protocol声明了可以呗其他任何方法类实现的方法,协议仅仅是定义一个接口,而由其他的类去负责实现。

2 代码实例

main.m:

#import <Foundation/Foundation.h>#import "ClassWithProtocol.h"#import "TestAppDelegate.h"int main(int argc, const char * argv[]){    @autoreleasepool {                ClassWithProtocol *another = [[ClassWithProtocol alloc] init];        TestAppDelegate *test =[[TestAppDelegate alloc] init];        //ClassWithProtocol的代理设置为TestAppDelegate        another.delegate = test;        //调用方法        [another processComplete];        [test release];        [another release];            }    return 0;}

ClassWithProtocol.h:

#import <Foundation/Foundation.h>#import "ProcessDataDelegate.h"@interface ClassWithProtocol : NSObject{    id<ProcessDataDelegate> delegate;}//设置代理@property (retain)id delegate;-(void)processComplete;@end

运行结果:

2013-05-17 14:44:06.022 ProtocolTest[623:303] Process completed

3 结语

以上是所有内容,希望对大家有所帮助。

Demo代码实例:http://download.csdn.net/detail/u010013695/5397059