码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-06-19 18:21:16      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:

转: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, its probably going to depend logically on the MySpecialViewController class. So, youre not introducing any additional dependencies.

But, theres another significant reason (at least) to use protocols. You might be trying to decouple a bidirectional dependency between two classes. Of course, the compiler doesnt let two headers #import one another. But, even if you move one classs #import to the .m file, its often a sign of a poor design to have two classes each fully aware of one anothers 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文件中?

标签:

原文地址:http://www.cnblogs.com/ygm900/p/4589375.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!