Problem with delegate and navigation controller

I am using NavigationController to push viewControllers from the root application.

I want to use delegates to communicate with the currently loaded view and the root controller. I was able to do this using NSNotificationCenter, but I want to try delegates for this particular situation, since the connection will always be one-to-one.

In the view that was clicked, I declared the following delegate prototype in the header file:

#import <UIKit/UIKit.h>

@protocol AnotherViewControllerDelegate;

@interface AnotherViewController : UIViewController {
    id <AnotherViewControllerDelegate> delegate;
}

- (IBAction) doAction;

@property (nonatomic, assign) id delegate;

@end


@protocol AnotherViewControllerDelegate <NSObject>
- (void) doDelegatedAction:(AnotherViewController *)controller;
@end

DoAction IBAction connects to the UIButton in the view. In my implementation file, I added:

#import "AnotherViewController.h"    
@implementation AnotherViewController

@synthesize delegate;

- (IBAction) doAction {
    NSLog(@"doAction");
    [self.delegate doDelegatedAction:self];
}

In my RootViewController.h, I added AnotherViewControllerDelegate to the interface declaration:

@interface RootViewController : UIViewController <AnotherViewControllerDelegate> {...

and this is for my implementation file

- (void) doDelegatedAction:(AnotherViewController *)controller {
    NSLog(@"rootviewcontroller->doDelegatedAction");
 }

, . doDelegatedAction rootViewController . - , AnotherViewController:

    AnotherViewController *detailViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherViewController" bundle:nil];
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];

- AnotherViewController, RootViewController ? - ?

+3
1

delegate of AnotherViewController rootViewController, .

AnotherViewController rootViewController, :

AnotherViewController *detailViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherViewController" bundle:nil];
detailViewController.delegate = self;
[self.navigationController pushViewController:detailViewController animated:YES];
+1

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


All Articles