Objective-C: Circular Protocol Requirements
I have 2 view controllers, an object picker and an object editor. Both of these objects have their own protocols to allow the presenters to receive data & dismiss them.
The editor sometimes needs to present a picker, and the 开发者_开发技巧picker needs to sometimes allow objects to be edited.
The problem is that there is a circular protocol dependancy, and as the objects have to conform to the protocols, declaration forwarding doesn't work (you still get compiler warnings).
I'm not just declaring an ivar that needs to conform to it, the whole picker/editor class needs to conform, thus the headers need the full information on the protocols.
I get a Cannot find protocol definition for 'EditorDelegate'
error.
Here's an example:
Picker.h
#import "Editor.h"
@protocol PickerDelegate;
@interface Picker : UIViewController <EditorDelegate> {
id <PickerDelegate> delegate;
}
@protocol PickerDelegate <NSObject>
- (void)picker:(Picker *) wasDismissedWithObject:(id)object;
@end
Editor.h
#import "Picker.h"
@protocol EditorDelegate;
@interface Editor : UIViewController <PickerDelegate> {
id <EditorDelegate> delegate;
}
@protocol EditorDelegate <NSObject>
- (void)editor:(Editor *) dismissedAfterEditingObject:(id)object;
@end
How can this be overcome?
Same files solution:
@protocol classBProtocol;
@protocol classAProtocol <NSObject>
-(void)fooA:(id<classBProtocol>)classB;
@end
#import "classB.h"
@interface classA : NSObject
@property (nonatomic) id<classBProtocol> delegate;
@end
and
@protocol classAProtocol;
@protocol classBProtocol <NSObject>
-(void)fooB:(id<classAProtocol>)classA;
@end
#import "classA.h"
@interface classB : NSObject
@property (nonatomic) id<classAProtocol> delegate;
@end
The trick here is to import headers after protocol declarations.
Can't you define the protocols in separate files, and import them in the .m files?
精彩评论