How to create delegation from child to parent (subview-superview)

I have worked with a delegation before. I know how to create delegation from supervisor to subview class. however, I am trying to do it the other way around using the same approach, but it does not work! Does delegation mean only working one way or is there a way / trick to use it as a two way communication between classes? I get an error in the parent / superview.h class, which is:

Cannot find protocol definition for "SubViewControllerDelegate"

my code is as follows: subview.h

#import <UIKit/UIKit.h> #import "SuperViewController.h" @protocol SubViewControllerDelegate <NSObject> - (void)someMethod:(NSData *)data; @end @interface SubViewController : UIViewController @property (weak, nonatomic) id <SubViewControllerDelegate> delegate; @end 

subview.m:

 [self.delegate someMethod:data]; 

SuperView.h

 #import <UIKit/UIKit.h> #import "SubViewController.h" @interface SuperViewController : UIViewController <SubViewControllerDelegate> @end 

SuperView.m:

 #pragma mark - SubView Controller Delegate Methods - (void)someMethod:(NSData *)data{ NSLog(@"%@", data); } 

Am I doing something wrong or missing something?

+4
source share
1 answer

You have an "import loop" because "SuperViewController.h" imports "SubViewController.h" and vice versa.

Removing #import "SuperViewController.h" in "SubViewController.h" should fix the problem.

If you really need this class to declare in "SubViewController.h", use @class SuperViewController; to avoid import cycle.

Note: The declaration of the <SubViewControllerDelegate> protocol is probably not necessary in the "SuperViewController.h" public interface.

In "SuperViewController.h" declare the class as

 @interface SuperViewController : UIViewController 

In "SuperViewController.m" define the class extension with the protocol:

 @interface SuperViewController () <SubViewControllerDelegate> @end 
+5
source

Source: https://habr.com/ru/post/1491064/


All Articles