Objective-C之@protocol

转自:http://www.cnblogs.com/hxxy2003/archive/2011/10/24/2222838.html

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

“代理”模式的使用:

1.接口声明

Objective-C之@protocol
Objective-C之@protocol
#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
Objective-C之@protocol
Objective-C之@protocol

2.接口回调

Objective-C之@protocol
Objective-C之@protocol
#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
Objective-C之@protocol
Objective-C之@protocol

3.接口实现

Objective-C之@protocol
Objective-C之@protocol
#import <UIKit/UIKit.h>
#import "ProtocolTest.h"

@class Test;

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

@property(nonatomic,retain)UIWindow *window;

@end
Objective-C之@protocol
Objective-C之@protocol
Objective-C之@protocol
Objective-C之@protocol
#import "Test.h"
#import "ProtocolTest.h"

@implementation Test

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


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

Objective-C之@protocol

上一篇:2012年Macbook Air安装window10双系统


下一篇:Git的撤消操作 - 重置, 签出 和 撤消(转载)