Objective-C之@protocol

@protocol是Objective-C中的接口定义方式,也就是说在一个类中通过@protocol定义接口,然后在另一个类中去实现这个接口,这也叫“代理”模式, 这种模式在ios开发中经常是会用到的。

“代理”模式的使用:

1.接口声明

#import <Foundation/Foundation.h>

//接口声明
@protocol ProtocolExampleDelegate <NSObject>
@required
-(void)successful:(BOOL)success;

@end

@interface ProtocolTest : NSObject{
//这个类包含该接口
id<ProtocolExampleDelegate> delegate;

}
//接口变量delegate作为类ProtocolTest的属性
@property(nonatomic,retain)id delegate;


//定义一个方法,使完成的时候回调接口
-(void)Complete;

@end

2.接口回调

#import "ProtocolTest.h"

@implementation ProtocolTest

@synthesize delegate;

-(void)complete
{
//回调接口,successful()由使用者负责具体实现
[[self delegate]successful:YES];
}

//通过定时器模拟在任务完成时调用接口回调函数
-(void)start
{
[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(complete) userInfo:nil repeats:YES];
}


@end

3.接口实现

#import <UIKit/UIKit.h>
#import "ProtocolTest.h"

@class Test;

@interface Test : NSObject<UIApplicationDelegate,ProtocolExampleDelegate>
{
UIWindow *window;
ProtocolTest *protocolTest;
}

@property(nonatomic,retain)UIWindow *window;

@end
#import "Test.h"
#import "ProtocolTest.h"

@implementation Test

@synthesize window;
//只实现一个方法
-(void)successful:(BOOL)success
{
NSLog(@"completed");
}


这个例子只是理解下@protocol.

posted @ 2011-10-24 16:54  寒星晓月 专注移动互联网  阅读(19866)  评论(3编辑  收藏  举报