Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using @class to get access to a delegate protocol declaration

I've read that you should try to use @class in your header file instead of #import but this doesn't work when your @class contains a delegate protocol that you're trying to use.

MyView.h

#import <UIKit/UIKit.h>
@class MyCustomClass;  // <-- doesn't work for MyCustomClassDelegate, used below

@interface MyView : UIView <MyCustomClassDelegate>

@end

I think I'm overlooking something, is there a way to get @class to work in this situation or is #import my only choice?

Edit: One work around for this is, of course, declaring your #import MyCustomClass and MyCustomClassDelegate in the private interface section of the .m file instead of the .h file.

like image 290
Travis M. Avatar asked Oct 21 '13 16:10

Travis M.


1 Answers

you can use @protocol to forward declare a protocol if you only need it for variables such as this:

@protocol MyProtocol;

@interface MyClass {
    id<MyProtocol> var;
}
@end

In your case the declared class is trying to conform to a protocol so the compiler must know about the protocol methods at this point in order to deduce weather or not the class conforms.

In this case, I think your options are to split the protocol into its own file and #import that header, or declare the protocol in that header above the class declaration that uses it.

like image 86
Brad Allred Avatar answered Oct 21 '22 13:10

Brad Allred