简体   繁体   English

什么时候在Objective-C中不使用协议代表?

[英]when use protocol not for a delegate in objective-c?

A protocol is a list of method statement , anyone who conforms to it must or may implement it . 协议是方法声明的列表,任何遵守它的人都必须或可以实现它。

In most cases,a delegate's implementation relies on protocol,such as below: 在大多数情况下,委托的实现取决于协议,例如:

@protocol VSActivateCouponDelegate <NSObject>
-(void)activateCouponSuccessWithActivateType:(ActivateType)type;
@end

My question is protocol's usage scenarios except implementing Delegate ? 我的问题是协议的使用场景,除了实现委托?

For example, any interface that you want to keep generic in terms of not knowing the exact class that will be providing a specific role in some relationship. 例如,在不知道将在某些关系中提供特定角色的确切类的情况下,要保持通用性的任何接口。 Delegate is one example of that but any relationship between two classes could use the same approach to abstraction. 委托就是一个例子,但是两个类之间的任何关系都可以使用相同的抽象方法。

Check out NSCopying , NSCoding etc. These are also protocols, but they are not used as delegates. NSCopyingNSCopyingNSCoding等。这些也是协议,但是不用作委托。

Let's look at NSCopying for example. 让我们以NSCopying为例。 If a class conforms to NSCopying , you know that you can call copy on any of its instances (and... copy it ), without even looking at the specific class, you can even pass instances as id<NSCopying> - this makes things more decoupled. 如果一个类符合NSCopying ,您知道您可以在其任何实例上调用copy (并... copy),而无需查看特定的类,您甚至可以将实例作为id<NSCopying>传递-这样就可以了更解耦。 For instance NSDictionary only accepts key values that are id<NSCopying> . 例如, NSDictionary仅接受id<NSCopying>键值。

To summarize, protocols let you declare behavior without coupling it to a specific class. 总而言之,协议允许您声明行为而不将其耦合到特定类。 It doesn't always have to be delegates. 它并不总是必须是委托人。

an example would be: 一个例子是:

say you have an array of arbitrary objects of arbitrary types. 说您有一个任意类型的任意对象数组。 now you want to make sure that all the objects at least have a certain function you can call on all of them to make them do something, then you can make all those objects conform to a protocol that has that method, thus making sure all the objects in that array have that certain functionality. 现在,您要确保所有对象至少具有某种功能,可以调用所有对象以使它们执行某些操作,然后可以使所有这些对象符合具有该方法的协议,从而确保所有对象该数组中的对象具有某些功能。

pseudo code of what that may look like: 如下所示的伪代码:

@protocol MyProtocol {
   - (void) doSomething;
}

//used somewhere
for(MyProtocol object in arrayOfUnknownObjects)
  [object doSomething]; //dont know what object's type is but we know it has [doSomething] method

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM