目录

Objective-C - 协议 Protocols

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

在上面的例子中,我们已经看到了如何调用和执行delgate方法。 它以startAction开始,一旦进程完成,就会调用委托方法processCompleted以使操作完成。

在任何iOS或Mac应用程序中,如果没有代理,我们将永远不会实现程序。 因此,重要的是我们了解代表的用法。 委托对象应使用unsafe_unretained属性类型以避免内存泄漏。

↑回到顶部↑
WIKI教程 @2018