James Weir
James Weir

Reputation: 135

Proper way to import delegate protocols

I try to import as very little as possible in my header files (using the implementation file instead), and for classes we can use @class, but what about protocols? If I try to declare a protocol that I'll be using in that header with @protocol I get a warning that "Cannot find protocol definition for '...'"

Is the proper way to handle this simply by importing the header that does the protocol declaration? (so one .h file imports the other .h)

Example for ListViewController.h:

#import <UIKit/UIKit.h>
#import "JTRevealSidebarV2Delegate.h"  // is this the best way?

@class List;

@protocol JTRevealSidebarV2Delegate;  // this produces a warning.

@interface ListViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, JTRevealSidebarV2Delegate>

Upvotes: 3

Views: 2498

Answers (3)

amar
amar

Reputation: 4343

Steps to do

  1. make a protocol.h file declare your @optional methods etc
  2. in your class A import protocol.h and implement the methods.
  3. Use reference of the calss A's obj to call its methods of protocol from any place.

Upvotes: 1

Ismael
Ismael

Reputation: 3937

It's correct, but if you want to get picky you can always create a single .h file where you declare your protocol only, and have both your ListViewController and JTRevealSidebarV2Delegate import it

Upvotes: 3

Stephen Darlington
Stephen Darlington

Reputation: 52565

You need the #import. @protocol doesn't give the compiler enough information to do its type checking.

(When you declare a property of type List all it needs to know is that you really mean List and not, say, Lisp. A pointer to any object is the same size. A protocol, on the other hand, contains a list of stuff that a class needs to do. It needs to know what "stuff" is to do anything useful.)

Upvotes: 5

Related Questions