I would like to know what is the difference when declaring a protocol in the same class and when declaring it in a separate file; example :
#import <UIKit/UIKit.h>
@class MyClassA;
@protocol MyDelegate <NSObject>
@required
- (MyClassA*)myMythod;
@optional
- (void)anOtherMethod:(NSString*)ID;
@end
@interface MyClassB : UIViewController <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, assign) id <MyDelegate> delegate;
......
here I declare the protocol delagate in the same file with MyClassB, and I can declare it (the protocol delegate) in a separate source file. What is the difference between declaring it in the same file with the class and in a separate file? Thanks!
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, andMySpecialViewControllerDelegate, 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 theMySpecialViewControllerclass. 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
#importone another. But, even if you move one class’s#importto 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
Parentowns and creates theChildclass, and thus must#import "Child.h". But, theChildalso needs to call thefoo:bar:method on theParent. You could make aFooProtocol:And then in Parent.h:
which allows
Childto do this:and use it
Which leaves the child with no direct dependency on the
Parentclass (or Parent.h). But, this only works if you keep the declaration ofFooProtocolin FooProtocol.h, not in Parent.h. Again, if thisFooProtocolwas only ever used byChild, then it would make sense to keep it in Child.h, but probably not if this protocol was used by classes other thanChild.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.