当前位置:首页 > 编程开发

The Basics of Protocols and Delegates

webgou14年前 (2013-01-09)编程开发122
Apple offers a good overview of working with protocols in their Objective-C Programming Reference. However, sometimes a simple working example can go a long ways… Introduction Protocols can be helpful in a number of scenarios, a common usage is to define methods that are to be implemented by other classes. A familiar example is when using a tableview, your class implements the cellForRowAtIndexPath method which asks for cell content to insert into a table – the cellForRowAtIndexPath method is defined within the UITableViewDataSource protocol. Let’s walk through a very simple example of defining and adopting a protocol. Protocol Definition Here is an example of a protocol which includes one method, notice the instance variable delegate is of type id, as it will be unknown at compile time the type of class that will adopt this protocol. #import @protocol ProcessDataDelegate @required - (void) processSuccessful: (BOOL)success; @end @interface ClassWithProtocol : NSObject { id delegate; } @property (retain) id delegate; -(void)startSomeProcess; @end Protocol Implementation Inside the implementation section for the interface defined above we need to do two things at a minimum – first synthesize the delegate instance variable and second, call the method defined in the protocol as needed (more on that in a moment). Let’s look at a bare bones implementation of the ClassWithProtocol.m: #import "ClassWithProtocol.h" @implementation ClassWithProtocol @synthesize delegate; - (void)processComplete { [[self delegate] processSuccessful:YES]; } -(void)startSomeProcess { [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(processComplete) userInfo:nil repeats:YES]; } @end Understand this is a rather contrived example – the intention is to show how/where one might use a protocol. For the sake of discussion assume you have a class that is processing (or downloading) some type of data. Further, assume this class is called from another class to begin the processing. Chances are, at some point the caller will want to be notified that the class processing the data is done, this is where the protocol comes in. In the calling class, the method defined in the protocol, processSuccessful, will be implemented and will be called from the object doing the processing, once it is complete. For this example, inside the class where the protocol is defined, I have one method, startSomeProcess, which simply starts a timer and calls processComplete after 5 seconds. Inside processComplete the calling object will be notified through its delegate that the process is done. Adopting the Protocol To keep the example short, I am using the applicaton delegate as the class that adopts the protocol. Here is how the app delegate looks: #import #import "ClassWithProtocol.h" @interface TestAppDelegate : NSObject { UIWindow *window; ClassWithProtocol *protocolTest; } @property (nonatomic, retain) UIWindow *window; @end A few things to note – ProcessDataDelegate is defined as part of the interface, which signifies that this class will adhere to the protocol. Looking back to the code for defining the protocol, notice that I added @required to the definition, which means that any class that adopts the protocol must implement the processSuccessful method (you will receive a compile warning if you don’t). Here is the implementation of the app delegate and the required method for the protocol: #import "TestAppDelegate.h" #import "ClassWithProtocol.h" @implementation TestAppDelegate @synthesize window; UITableViewDelegate - (void)processSuccessful:(BOOL)success; { NSLog(@"Process completed"); } - (void)applicationDidFinishLaunching:(UIApplication *)application { // Create and initialize the window window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; protocolTest = [[ClassWithProtocol alloc] init]; [protocolTest setDelegate:self]; [protocolTest startSomeProcess]; [window makeKeyAndVisible]; } - (void)dealloc { [window release]; [super dealloc]; } @end How it all works Things goes as follows: the app delegate will create a new instance of the ClassWithProtocol object. It sets itself as the delegate and then calls the startSomeProcess method. At some point in the future, when the protocolTest object has completed its work – after the 5 second timer has fired – it will call the processSuccessful method in the app delegate to let it know it is done processing. Download Xcode Project You can find a complete (albeit trivial) working example here: Protocol Xcode Project link:http://mobiledevelopertips.com/objective-c/the-basics-of-protocols-and-delegates.html

扫描二维码推送至手机访问。

版权声明:本文由知了博客发布,如需转载请注明出处。

本文链接:https://www.webgou.info/?id=539

分享给朋友:

“The Basics of Protocols and Delegates” 的相关文章

[转]Apktool(1)——Apktool的安装

 来源:https://www.cnblogs.com/mliangchen/p/5079783.htmlApktool(1)——Apktool的安装...…

C语言版GDI+应用例子 -- 画刷

    GDI+提供了SolidBrush(实色刷)、HatchBrush(阴影刷)、TextureBrush(纹理刷)、LinearGradientBrush(渐变刷)和PathGradientBrush(路径刷)等五种画刷,在GDI+的C语言版本中,这些画…

如何诊断Windows CE的应用程序崩溃(Remote Process Explorer使用)

如何诊断Windows CE的应用程序崩溃(Remote Process Explorer使用)…

多线程中生成随机数序列重复问题的解决方法

使用过随机数的程序员都知道在程序中并不能够实现的真正的完全的随机数函数。随机数函数产生的是通过公式计算出来的一系列伪随机数,这个公式会采用一个种子数计算出一个数,而该数将成为产生下一个数的种子数。基于产生随机数的原理,两次调用随机数后产生的随机数序列将是一样的,显然,这不是我们的期望的结果。....…

linux下的tar打包命令示例及详解

[root@linux tmp]# tar -zxvf /tmp/etc.tar.gz etc/passwd ....…

虚幻4(ue4)引擎加密pak解包教程(初学者向x64源码逆向)

 前言  遇到了喜欢的游戏,想提取壁纸,于是找quickbms等虚幻4引擎解包工具。无奈游戏加密,无法解包。不知密钥情况下,也没在网上找到现成的加密pak解包工具。想到Unreal4已经开源,就尝试着自己找一下密钥,也算是对照源码的x64逆向分析调试。以前接触的Olly…

发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。