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;
}

执行上面示例代码,得到以下结果 -

2018-11-16 03:10:19.639 main[18897] Printing Details
2018-11-16 03:10:19.641 main[18897] Printing Process Completed

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

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