1

I am trying to create several protocols, and most of them have references to other ones. But I get error during the build process.

I give an example:

#import <Foundation/Foundation.h>

@protocol DataChildDelegate <NSObject>

@property(nonatomic) id<DataParentDelegate> parent;

@end

@protocol DataParentDelegate <NSObject>

@property(nonatomic) id<DataChildDelegate> firstChild;
@property(nonatomic) id<DataChildDelegate> lastChild;

@end

I tried to divide DataChildDelegate in two parts like this:

#import <Foundation/Foundation.h>

@protocol DataChildDelegate <NSObject>
@end

@protocol DataParentDelegate <NSObject>

@property(nonatomic) id<DataChildDelegate> firstChild;
@property(nonatomic) id<DataChildDelegate> lastChild;

@end

@protocol DataChildDelegate <NSObject>

@property(nonatomic) id<DataParentDelegate> parent;

@end

But this time I get a warning.

Is there any more suitable way to handle this problem?

Thanks

Rephisto
  • 89
  • 1
  • 7

1 Answers1

2

You should use a forward declaration of the protocol DataChildDelegate prior to DataParentDelegate so that the compiler can trust that it exists.

For example:

#import <Foundation/Foundation.h>

@protocol DataChildDelegate;     /*Forward declaration of DataChildDelegate */

@protocol DataParentDelegate <NSObject>

@property(nonatomic) id<DataChildDelegate> firstChild;
@property(nonatomic) id<DataChildDelegate> lastChild;

@end

@protocol DataChildDelegate <NSObject>

@property(nonatomic) id<DataParentDelegate> parent;

@end
wmorrison365
  • 5,995
  • 2
  • 27
  • 40
  • FYI: see also http://stackoverflow.com/q/11532888/758831 and http://stackoverflow.com/a/11091897/758831 for more specifics on the use of forward declarations. – wmorrison365 Feb 03 '14 at 12:06