[Objective-C] Protocol 简介
2015-07-10 09:41
543 查看
转自:http://rypress.com/tutorials/objective-c/protocols
A protocol is a group of related properties and methods that can be implemented by any class. They are more flexible than
a normal class interface, since they let you reuse a single API declaration in completely unrelated classes. This makes it possible to represent horizontal relationships on top of an existing class hierarchy.
【yasi】protocol 定义一组相关属性和方法,protocol自己不做实现。任意类都可以遵从同一个protocol,并实现其方法。这样可以使得,不相关的任何类都遵从同一套协议,在运行时具有灵活性。
Unrelated classes adopting the
This is a relatively short module covering the basics behind working with protocols. We’ll also see how they fit into Objective-C’s dynamic typing system.
Like class interfaces, protocols typically reside in a
use the Cmd+N shortcut. Select Objective-C protocol under theiOS > Cocoa Touch category.
Creating a protocol in Xcode
In this module, we’ll be working with a protocol called
root.
Our protocol will capture the necessary behaviors of a street-legal vehicle. Defining these characteristics in a protocol lets you apply them to arbitrary objects instead of forcing them to inherit from the same
abstract superclass. A simple version of the
[/code]
Any objects that adopt this protocol are guaranteed to implement all of the above methods. The
the protocol name incorporates the
to be confused with the
into the
are required to conform to the
The above API can be adopted by a class by adding it in angled brackets after the class/superclass name. Create a new classed called
change its header to the following. Note that you need to import the protocol before you can use it.
【yasi】通过类似 @interface Bicycle: NSObject<StreatLega> 的方式就可以让 Bicyle 类遵从 StreetLegal 协议。遵从协议的类必须确保实现 protocol 中的所有 @required 方法,可以选择实现 @optional 方法
[/code]
Adopting the protocol is like adding all of the methods in
This would work the exact same way even if
There’s nothing special about the
implemented:
[/code]
Now, when you use the
and
【yasi】对遵从同一个protocol的多个类的对象,都可以调用protocol中任何方法
[/code]
Just like classes, protocols can be used to type check variables. To make sure an object adopts a protocol, put the protocol name after the data type in the variable declaration, as shown below. The next code
snippet also assumes that you have created a
[/code]
It doesn’t matter if
from the same superclass—the fact that they both adopt the
Objects can also be checked against a protocol using the
It takes a protocol object as an argument, which can be obtained via the
but you pass the protocol name instead of a method name, like so:
【yasi】可以通过 conformsToProtocol 方法判断一个类的对象是否遵从某个 protocol,如果遵从,则对该对象执行protocol 中的方法
[/code]
Using protocols in this manner is like saying, “Make sure this object has this particular set of functionality.” This is a very powerful tool for dynamic typing, as it lets you use a well-defined API without worrying
about what kind of object you’re dealing with.
A more realistic use case can be seen in your everyday iOS and OS X application development. The entry point into any app is an “application delegate” object that handles the major events in a program’s life cycle.
Instead of forcing the delegate to inherit from any particular superclass, the UIKit
Framework just makes you adopt a protocol:
[/code]
As long as it responds to the methods defined by
you can use any object as your application delegate. Implementing the delegate design pattern through protocols instead of subclassing gives developers much more leeway
when it comes to organizing their applications.
You can see a concrete example of this in the Interface
Builderchapter of Ry’s Cocoa Tutorial. It uses the project’s default app delegate to respond to
user input.
In this module, we added another organizational tool to our collection. Protocols are a way to abstract shared properties and methods into a dedicated file. This helps reduce redundant code and lets you dynamically
check if an object supports an arbitrary set of functionality.
You’ll find many protocols throughout the Cocoa frameworks. A common use case is to let you alter the behavior of certain classes without the need to subclass them. For instance, the Table
View,Outline
View, and Collection
View UI components all use a data source and delegate object to configure their internal behavior. The data source and delegate are defined as protocols, so you can implement the necessary methods in any object
you want.
The next module introduces categories, which are a flexible option for modularizing classes and providing opt-in support for an API.
A protocol is a group of related properties and methods that can be implemented by any class. They are more flexible than
a normal class interface, since they let you reuse a single API declaration in completely unrelated classes. This makes it possible to represent horizontal relationships on top of an existing class hierarchy.
【yasi】protocol 定义一组相关属性和方法,protocol自己不做实现。任意类都可以遵从同一个protocol,并实现其方法。这样可以使得,不相关的任何类都遵从同一套协议,在运行时具有灵活性。
Unrelated classes adopting the
StreetLegalprotocol
This is a relatively short module covering the basics behind working with protocols. We’ll also see how they fit into Objective-C’s dynamic typing system.
Creating Protocols
Like class interfaces, protocols typically reside in a .hfile. To add a protocol to your Xcode project, navigate to File > New> File… or
use the Cmd+N shortcut. Select Objective-C protocol under theiOS > Cocoa Touch category.
Creating a protocol in Xcode
In this module, we’ll be working with a protocol called
StreetLegal. Enter this in the next window, and save it in the project
root.
Our protocol will capture the necessary behaviors of a street-legal vehicle. Defining these characteristics in a protocol lets you apply them to arbitrary objects instead of forcing them to inherit from the same
abstract superclass. A simple version of the
StreetLegalprotocol might look something like the following:
// StreetLegal.h
#import
<Foundation/Foundation.h>
@protocol
StreetLegal
<NSObject>
-
(
void
)
signalStop
;
-
(
void
)
signalLeftTurn
;
-
(
void
)
signalRightTurn
;
@end
[/code]
Any objects that adopt this protocol are guaranteed to implement all of the above methods. The
<NSObject>after
the protocol name incorporates the
NSObjectprotocol (not
to be confused with the
NSObjectclass)
into the
StreetLegalprotocol. That is, any objects conforming to the
StreetLegalprotocol
are required to conform to the
NSObjectprotocol, too.
Adopting Protocols
The above API can be adopted by a class by adding it in angled brackets after the class/superclass name. Create a new classed calledBicycleand
change its header to the following. Note that you need to import the protocol before you can use it.
【yasi】通过类似 @interface Bicycle: NSObject<StreatLega> 的方式就可以让 Bicyle 类遵从 StreetLegal 协议。遵从协议的类必须确保实现 protocol 中的所有 @required 方法,可以选择实现 @optional 方法
// Bicycle.h
#import
<Foundation/Foundation.h>
#import
"StreetLegal.h"
@interface
Bicycle:
NSObject
<StreetLegal>
-
(
void
)
startPedaling
;
-
(
void
)
removeFrontWheel
;
-
(
void
)
lockToStructure:
(
id
)
theStructure
;
@end
[/code]
Adopting the protocol is like adding all of the methods in
StreetLegal.hto
Bicycle.h.
This would work the exact same way even if
Bicycleinherited from a different superclass. Multiple protocols can be adopted by separating them with commas (e.g.,
<StreetLegal, SomeOtherProtocol>).
There’s nothing special about the
Bicycleimplementation—it just has to make sure all of the methods declared by
Bicycle.hand
StreetLegal.hare
implemented:
// Bicycle.m
#import
"Bicycle.h"
@implementation
Bicycle
-
(
void
)
signalStop
{
NSLog
(
@"Bending left arm downwards"
);
}
-
(
void
)
signalLeftTurn
{
NSLog
(
@"Extending left arm outwards"
);
}
-
(
void
)
signalRightTurn
{
NSLog
(
@"Bending left arm upwards"
);
}
-
(
void
)
startPedaling
{
NSLog
(
@"Here we go!"
);
}
-
(
void
)
removeFrontWheel
{
NSLog
(
@"Front wheel is off."
"Should probably replace that before pedaling..."
);
}
-
(
void
)
lockToStructure:
(
id
)
theStructure
{
NSLog
(
@"Locked to structure. Don't forget the combination!"
);
}
@end
[/code]
Now, when you use the
Bicycleclass, you can assume it responds to the API defined by the protocol. It’s as though
signalStop,
signalLeftTurn,
and
signalRightTurnwere declared in
Bicycle.h:
【yasi】对遵从同一个protocol的多个类的对象,都可以调用protocol中任何方法
// main.m
#import
<Foundation/Foundation.h>
#import
"Bicycle.h"
int
main
(
int
argc
,
const
char
*
argv
[])
{
@autoreleasepool
{
Bicycle
*
bike
=
[[
Bicycle
alloc
]
init
];
[
bike
startPedaling
];
[
bike
signalLeftTurn
];
[
bike
signalStop
];
[
bike
lockToStructure:
nil
];
}
return
0
;
}
[/code]
Type Checking With Protocols
Just like classes, protocols can be used to type check variables. To make sure an object adopts a protocol, put the protocol name after the data type in the variable declaration, as shown below. The next codesnippet also assumes that you have created a
Carclass that adopts the
StreetLegalprotocol:
// main.m
#import
<Foundation/Foundation.h>
#import
"Bicycle.h"
#import
"Car.h"
#import
"StreetLegal.h"
int
main
(
int
argc
,
const
char
*
argv
[])
{
@autoreleasepool
{
id
<StreetLegal>
mysteryVehicle
=
[[
Car
alloc
]
init
];
[
mysteryVehicle
signalLeftTurn
];
mysteryVehicle
=
[[
Bicycle
alloc
]
init
];
[
mysteryVehicle
signalLeftTurn
];
}
return
0
;
}
[/code]
It doesn’t matter if
Carand
Bicycleinherit
from the same superclass—the fact that they both adopt the
StreetLegalprotocol lets us store either of them in a variable declared with
id <StreetLegal>. This is an example of how protocols can capture common functionality between unrelated classes.
Objects can also be checked against a protocol using the
conformsToProtocol:method defined by the
NSObjectprotocol.
It takes a protocol object as an argument, which can be obtained via the
@protocol()directive. This works much like the
@selector()directive,
but you pass the protocol name instead of a method name, like so:
【yasi】可以通过 conformsToProtocol 方法判断一个类的对象是否遵从某个 protocol,如果遵从,则对该对象执行protocol 中的方法
if
([
mysteryVehicle
conformsToProtocol:
@protocol
(
StreetLegal
)])
{
[
mysteryVehicle
signalStop
];
[
mysteryVehicle
signalLeftTurn
];
[
mysteryVehicle
signalRightTurn
];
}
[/code]
Using protocols in this manner is like saying, “Make sure this object has this particular set of functionality.” This is a very powerful tool for dynamic typing, as it lets you use a well-defined API without worrying
about what kind of object you’re dealing with.
Protocols In The Real World
A more realistic use case can be seen in your everyday iOS and OS X application development. The entry point into any app is an “application delegate” object that handles the major events in a program’s life cycle.Instead of forcing the delegate to inherit from any particular superclass, the UIKit
Framework just makes you adopt a protocol:
@interface
YourAppDelegate:
UIResponder
<UIApplicationDelegate>
[/code]
As long as it responds to the methods defined by
UIApplicationDelegate,
you can use any object as your application delegate. Implementing the delegate design pattern through protocols instead of subclassing gives developers much more leeway
when it comes to organizing their applications.
You can see a concrete example of this in the Interface
Builderchapter of Ry’s Cocoa Tutorial. It uses the project’s default app delegate to respond to
user input.
Summary
In this module, we added another organizational tool to our collection. Protocols are a way to abstract shared properties and methods into a dedicated file. This helps reduce redundant code and lets you dynamicallycheck if an object supports an arbitrary set of functionality.
You’ll find many protocols throughout the Cocoa frameworks. A common use case is to let you alter the behavior of certain classes without the need to subclass them. For instance, the Table
View,Outline
View, and Collection
View UI components all use a data source and delegate object to configure their internal behavior. The data source and delegate are defined as protocols, so you can implement the necessary methods in any object
you want.
The next module introduces categories, which are a flexible option for modularizing classes and providing opt-in support for an API.
相关文章推荐
- Objective-C知识整理——实例变量修饰符
- function invoke objects DEMO
- [Objective-C] strong/weak 属性——狗项圈的比喻
- GitHub 上排名前 100 的 Objective-C 项目简介
- interweaving of objects DEMO
- 黑马程序员 面向对象 多态 需求 object
- [Objective-C] self 和 this 的区别
- Java 兑换ObjectC代码
- ObjectStreamDemo
- [学习笔记—Objective-C]《Objective-C 程序设计 第6版》第十七章 内存管理和自动计数
- 编写高质量的Objective-C代码(转)
- Objective-C(十八、谓语使用及实例说明)——iOS开发基础
- java查询mysql的char字段List<Object[]>数据被截断
- Objective-c中 isEqual ,isEqualToString , == 三者的区别
- Objective-C 计算文件夹里的代码行数
- Objective-C(十七、KVC键值编码及实例说明)——iOS开发基础
- Objective-C(十六、内存管理,自动释放池,ARC,强指针,弱指针,方法族)——iOS开发基础
- 总结js创建object的方式(对象)
- Windows下安装Object C开发环境,及Hello Word
- objective-c之Foundation