delegate 集成在类中,还是单独写在.h文件中?

转:http://stackoverflow.com/questions/11382057/declaring-a-delegate-protocol

There definitely are subtle differences.

If the protocol you are talking about is a delegate that is used by one particular class, for example, MySpecialViewController, and MySpecialViewControllerDelegate, then you might very well like to keep the declaration of both of those in the same header. If another class is going to implement that protocol, for example, it's probably going to depend logically on the MySpecialViewController class. So, you're not introducing any additional dependencies.

But, there's another significant reason (at least) to use protocols. You might be trying to decouple a bidirectional dependency between two classes. Of course, the compiler doesn't let two headers #import one another. But, even if you move one class's #import to the .m file, it's often a sign of a poor design to have two classes each fully aware of one another's complete API.

One way to decouple this relationship a little is to make one class aware of the other only through a protocol that the other implements. Perhaps Parent owns and creates the Child class, and thus must #import "Child.h". But, the Child also needs to call the foo:bar: method on the Parent. You could make a FooProtocol:

@protocol FooProtocol
  - (void) foo: (int) arg1 bar: (BOOL) arg2;
@end
And then in Parent.h:

@interface Parent : SomeBaseClass<FooProtocol> {
}
which allows Child to do this:

@interface Child {
}
@property (assign) id<FooProtocol> fooHandler;
and use it

[fooHandler foo: 1 bar: YES];
Which leaves the child with no direct dependency on the Parent class (or Parent.h). But, this only works if you keep the declaration of FooProtocol in FooProtocol.h, not in Parent.h. Again, if this FooProtocol was only ever used by Child, then it would make sense to keep it in Child.h, but probably not if this protocol was used by classes other than Child.

So, to summarize, keep your protocols in separate headers if you want to preserve the maximum ability to separate interdependencies between your classes, or to encourage better separation in your design.

##百度视频iOS版delegate 单独写在一个.h文件中。

腾讯视频亦将delegate写在单独的.h文件中

 

posted @ 2015-06-19 17:51  ygm900  阅读(481)  评论(0编辑  收藏  举报