[Objective-C语言教程]协议(31)

Objective-C允许定义协议,声明预期用于特定情况的方法。 协议在符合协议的类中实现。

一个简单的例子是网络URL处理类,它将具有一个协议,其中包含processCompleted委托方法等方法,当网络URL提取操作结束,就会调用类。

协议的语法如下所示 -

1 @protocol ProtocolName
2 @required
3 // list of required methods
4 @optional
5 // list of optional methods
6 @end

关键字@required下的方法必须在符合协议的类中实现,并且@optional关键字下的方法是可选的。

以下是符合协议的类的语法 -

1 @interface MyClass : NSObject <MyProtocol>
2 ...
3 @end

MyClass的任何实例不仅会响应接口中特定声明的方法,而且MyClass还会为MyProtocol中的所需方法提供实现。 没有必要在类接口中重新声明协议方法 - 采用协议就足够了。

如果需要一个类来采用多个协议,则可以将它们指定为以逗号分隔的列表。下面有一个委托对象,它包含实现协议的调用对象的引用。

一个例子如下所示 -

 1 #import <Foundation/Foundation.h>
 2 
 3 @protocol PrintProtocolDelegate
 4 - (void)processCompleted;
 5 
 6 @end
 7 
 8 @interface PrintClass :NSObject {
 9    id delegate;
10 }
11 
12 - (void) printDetails;
13 - (void) setDelegate:(id)newDelegate;
14 @end
15 
16 @implementation PrintClass
17 - (void)printDetails {
18    NSLog(@"Printing Details");
19    [delegate processCompleted];
20 }
21 
22 - (void) setDelegate:(id)newDelegate {
23    delegate = newDelegate;
24 }
25 
26 @end
27 
28 @interface SampleClass:NSObject<PrintProtocolDelegate>
29 - (void)startAction;
30 
31 @end
32 
33 @implementation SampleClass
34 - (void)startAction {
35    PrintClass *printClass = [[PrintClass alloc]init];
36    [printClass setDelegate:self];
37    [printClass printDetails];
38 }
39 
40 -(void)processCompleted {
41    NSLog(@"Printing Process Completed");
42 }
43 
44 @end
45 
46 int main(int argc, const char * argv[]) {
47    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
48    SampleClass *sampleClass = [[SampleClass alloc]init];
49    [sampleClass startAction];
50    [pool drain];
51    return 0;
52 }

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

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

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

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

猜你喜欢

转载自www.cnblogs.com/strengthen/p/10572054.html