Objective-C allows you to define protocols, which declare the methods expected to be used for a particular situation. Protocols are implemented in the classes conforming to the protocol.

A simple example would be a network URL handling class, it will have a protocol with methods like processCompleted delegate method that intimates the calling class once the network URL fetching operation is over.

A syntax of protocol is shown below.

@protocol ProtocolName
@required
// list of required methods
@optional
// list of optional methods
@end

The methods under keyword @required must be implemented in the classes that conforms to the protocol and the methods under @optional keyword are optional to implement.

Here is the syntax for class conforming to protocol

@interface MyClass : NSObject <MyProtocol>
...
@end

This means that any instance of MyClass will respond not only to the methods declared specifically in the interface, but that MyClass also provides implementations for the required methods in MyProtocol. There's no need to redeclare the protocol methods in the class interface - the adoption of the protocol is sufficient.

If you need a class to adopt multiple protocols, you can specify them as a comma-separated list. We have a delegate object that holds the reference of the calling object that implements the protocol.

An example is shown below.

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

Now when we compile and run the program, we will get the following result.

-- ::50.362 Protocols[:] Printing Details
-- ::50.364 Protocols[:] Printing Process Completed

In the above example we have seen how the delgate methods are called and executed. Its starts with startAction, once the process is completed, the delegate method processCompleted is called to intimate the operation is completed.

In any iOS or Mac app, we will never have a program implemented without a delegate. So its important we understand the usage of delegates. Delegates objects should use unsafe_unretained property type to avoid memory leaks.

Objective-C Protocols的更多相关文章

  1. Automake

    Automake是用来根据Makefile.am生成Makefile.in的工具 标准Makefile目标 'make all' Build programs, libraries, document ...

  2. 刨根问底Objective-C Runtime

    http://chun.tips/blog/2014/11/05/bao-gen-wen-di-objective%5Bnil%5Dc-runtime-(2)%5Bnil%5D-object-and- ...

  3. 【Xamarin笔记】Events, Protocols and Delegates

    Events, Protocols and Delegates   事件.协议和委托 This article presents the key iOS technologies used to re ...

  4. 刨根问底Objective-C Runtime(4)- 成员变量与属性

    http://chun.tips/blog/2014/11/08/bao-gen-wen-di-objective[nil]c-runtime(4)[nil]-cheng-yuan-bian-lian ...

  5. Objective -C Categories

    Objective -C Categories  The dynamic runtime dispatch mechanism employed by Objective-C lets you add ...

  6. [Erlang 0112] Elixir Protocols

    Why Elixir   为什么要学习Elixir?答案很简单,为了更好的学习Erlang.这么无厘头的理由? Erlang语法设计几乎没有考虑过取悦开发者,所以学习之初的门槛略高.对于已经克服了最初 ...

  7. Objective C中的ARC的修饰符的使用---- 学习笔记九

    #import <Foundation/Foundation.h> @interface Test : NSObject /** * 默认的就是__strong,这里只是做示范,实际使用时 ...

  8. Level Of Management Protocols - SNMP Tutorial

    30.2 The Level Of Management Protocols Originally, many wide area networks included management proto ...

  9. Objective-O Runtime 运行时初体验

    Objective-C语言是一门动态语言,它将很多静态语言在编译和链接时期做的事放到了运行时来处理.这种动态语言的优势在于:我们写代码时更具灵活性,如我们可以把消息转发给我们想要的对象,或者随意交换一 ...

  10. Objective的字符串拼接 似乎没有Swift方便,但也可以制做一些较为方便的写法

    NSString *str1 = @"字符串1"; NSString *str2 = @"字符串2"; //在同样条件下,Objective的字符串拼接 往往只 ...

随机推荐

  1. vue render函数使用jsx语法 可以使用v-model语法 vuex实现数据持久化

    render函数使用jsx语法: 安装插件  transform-vue-jsx 可以使用v-model语法安装插件 jsx-v-model .babelrc文件配置: vuex实现数据持久化 安装插 ...

  2. node.js 安装 和 配置Sublime Text的Node.js

    安装node.js 第一步:下载安装文件: https://nodejs.org/en/download/ 第二步:安装nodejs 下载完成之后,双击"node-v6.10.1-x64.m ...

  3. [转载]Doxygen C++ 注释风格

    转载自:http://luchenqun.com/?p=761 做一个C++方面的符合Doxygen的注释文档,备用. 1.头文件根原文件注释.这个我也不知道需要注释什么.能想到的是:谁写的,里面有些 ...

  4. 一、使用 BeautifulSoup抓取网页信息信息

    一.解析网页信息 from bs4 import BeautifulSoup with open('C:/Users/michael/Desktop/Plan-for-combating-master ...

  5. java集合框架之几种set(HashSet LinkedHashSet TreeSet )

    参考http://how2j.cn/k/collection/collection-sets/691.html#nowhere HashSet LinkedHashSet TreeSet HashSe ...

  6. python3 封装之property 多态 绑定方法classmethod 与 非绑定方法 staticmethod

    property 特性 什么是特性property property 是一种特殊的属性,访问它时会执行一段功能(函数),然后返回值 例如 BMI指数(bmi是计算而来的,但很明显它听起来像是一个属性而 ...

  7. UVa 1631 Locker (DP)

    题意:有一个 n 位密码锁,每位都是0-9,可以循环旋转.同时可以让1-3个相邻数字进行旋转一个,给定初始状态和目状态,问你最少要转多少次. 析:很明显的一个DP题.dp[i][j][k] 表示前 i ...

  8. c# 字符串大小写转换

    //小转大 string lower = "converted from lowercase"; Console.WriteLine(lower.ToUpper()); //大转小 ...

  9. CodeForces 41A+43A【课上无聊刷水题系列】

    41Acode 好像只要前一个字符串存在下一个字符串的头单词就YES: #include <bits/stdc++.h> using namespace std; typedef __in ...

  10. Android开发实践:掌握Camera的预览方向和拍照方向

    http://ticktick.blog.51cto.com/823160/1592267?utm_source=tuicool&utm_medium=referral Android的Cam ...