aherlambang
aherlambang

Reputation: 14418

UIViewController calling each other's delegate

I have two UIViewController, each has it's delegate and is calling one or the other. One class is called TopicViewController and the other is MentionViewController, the code looks something like the following:

#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#import <RestKit/RestKit.h>
#import "Message.h"
#import "Imgur.h"
#import "URLViewController.h"
#import "CVore.h"
#import "NSData+Base64.h"
#import "Imgur.h"
#import "ProfileViewController.h"
#import "OptionsViewController.h"
#import "Three20/Three20.h"


@class DetailViewController;
@class MentionViewController;

@protocol DetailViewControllerDelegate

- (void) viewController:(DetailViewController*)viewCon withText:(NSString *) text;

@end


@interface DetailViewController : UIViewController <MentionViewControllerDelegate>


///////////////////////////////////////////////////////////////////////////////////

#import <UIKit/UIKit.h>
#import <RestKit/RestKit.h>
#import "Members.h"
#import "DetailViewController.h"
#import "Three20/Three20.h"

@class MentionViewController;

@protocol MentionViewControllerDelegate

- (void) viewController:(MentionViewController*)viewCon withUsername:(NSString *) text;

@end


@interface MentionViewController : UITableViewController <DetailViewControllerDelegate>

Now the problem is that when I add #import "MentionViewController.h" to the DetailViewController it gives me the following error in the MentioViewController:

Cannot find protocol declaration for DetailViewControllerDelegate.

I understand this might be due to cylical referencing, but how do I solve this?

Upvotes: 2

Views: 1607

Answers (3)

AechoLiu
AechoLiu

Reputation: 18368

It is really strange. The MentionViewController needs the header file of DetailViewController, and the DetailViewController needs MentionViewController's header file. It is a cycle. Maybe you need to create a empty header file, and put all protocol inside it. For example,

MyProtocol.h

@class DetailViewController;
@class MentionViewController;

@protocol DetailViewControllerDelegate

- (void) viewController:(DetailViewController*)viewCon withText:(NSString *) text;

@end

@protocol MentionViewControllerDelegate

- (void) viewController:(MentionViewController*)viewCon withUsername:(NSString *) text;

@end

And add #import MyProtocol.h inside DetailViewController.h and MentionViewController.h.

Upvotes: 9

sergio
sergio

Reputation: 69027

I think your intuition is correct.

You should be able to solve this problem by declaring the 2 protocols in a header file of their own, then import this file from your .m files. This will break the cycle.

Upvotes: 1

aegzorz
aegzorz

Reputation: 2219

You need to use forward declaration for the protocols and only import the headers in the implementation file.

Upvotes: 5

Related Questions