- Objective-C 基础
- Objective-C - 首页
- Objective-C - 概述
- Objective-C - 环境搭建
- Objective-C - 程序结构
- Objective-C - 基本语法
- Objective-C - 数据类型
- Objective-C - 变量
- Objective-C - 常量
- Objective-C - 运算符
- Objective-C - 循环
- Objective-C - 条件语句
- Objective-C - 函数
- Objective-C - 块 (Blocks)
- Objective-C - 数字
- Objective-C - 数组
- Objective-C - 指针
- Objective-C - 字符串
- Objective-C - 结构体
- Objective-C - 预处理器
- Objective-C - Typedef
- Objective-C - 类型转换
- Objective-C - 日志处理
- Objective-C - 错误处理
- 命令行参数
- 高级 Objective-C
- Objective-C - 类与对象
- Objective-C - 继承
- Objective-C - 多态
- Objective-C - 数据封装
- Objective-C - 分类 (Categories)
- Objective-C - 伪装 (Posing)
- Objective-C - 扩展 (Extensions)
- Objective-C - 协议
- Objective-C - 动态绑定
- Objective-C - 复合对象
- Obj-C - Foundation 框架
- Objective-C - 快速枚举
- Obj-C - 内存管理
- Objective-C 有用资源
- Objective-C - 快速指南
- Objective-C - 有用资源
- Objective-C - 讨论
Objective-C 协议
Objective-C 允许你定义协议,这些协议声明了特定情况下预期使用的的方法。协议在符合该协议的类中实现。
一个简单的例子是一个网络 URL 处理类,它将有一个包含诸如 processCompleted 代理方法的协议,该方法在网络 URL 获取操作完成后通知调用类。
下面显示了协议的语法。
@protocol ProtocolName @required // list of required methods @optional // list of optional methods @end
@required 关键字下的方法必须在符合该协议的类中实现,而 @optional 关键字下的方法则可以选择实现。
以下是类符合协议的语法
@interface MyClass : NSObject <MyProtocol> ... @end
这意味着 MyClass 的任何实例不仅会响应在接口中专门声明的方法,而且 MyClass 还提供了 MyProtocol 中必需方法的实现。无需在类接口中重新声明协议方法 - 采用协议就足够了。
如果需要一个类采用多个协议,可以将它们指定为用逗号分隔的列表。我们有一个代理对象,它保存实现该协议的调用对象的引用。
下面是一个例子。
#import <Foundation/Foundation.h>
@protocol PrintProtocolDelegate
- (void)processCompleted;
@end
@interface PrintClass :NSObject {
id delegate;
}
- (void) printDetails;
- (void) setDelegate:(id)newDelegate;
@end
@implementation PrintClass
- (void)printDetails {
NSLog(@"Printing Details");
[delegate processCompleted];
}
- (void) setDelegate:(id)newDelegate {
delegate = newDelegate;
}
@end
@interface SampleClass:NSObject<PrintProtocolDelegate>
- (void)startAction;
@end
@implementation SampleClass
- (void)startAction {
PrintClass *printClass = [[PrintClass alloc]init];
[printClass setDelegate:self];
[printClass printDetails];
}
-(void)processCompleted {
NSLog(@"Printing Process Completed");
}
@end
int main(int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
SampleClass *sampleClass = [[SampleClass alloc]init];
[sampleClass startAction];
[pool drain];
return 0;
}
现在,当我们编译并运行程序时,我们将得到以下结果。
2013-09-22 21:15:50.362 Protocols[275:303] Printing Details 2013-09-22 21:15:50.364 Protocols[275:303] Printing Process Completed
在上面的例子中,我们看到了代理方法是如何被调用和执行的。它从 startAction 开始,一旦进程完成,就会调用代理方法 processCompleted 来通知操作已完成。
在任何 iOS 或 Mac 应用程序中,我们都不会实现没有代理的程序。因此,理解代理的使用非常重要。代理对象应该使用 unsafe_unretained 属性类型来避免内存泄漏。
广告