0

Edit: I've since learned that what I was doing is very, very poor design. Do not do what I did. Instead, consider reading up on how MVC works, and making proper classes. Do not substitute controllers for objects.

Not sure if I'm going about my architecture the proper way, but what I'm doing is declaring an app delegate in each of my view controllers, and then giving the app delegate it's own view controller delegate for each view controller.

I end up adding the same three lines to each view controller, and another view controller to the app delegate each time I create a new view controller. Is there an easier way to do this with inheritance (I.E. give all view controllers an appDelegate property, then assign it in some parent function).

Here's what I'm currently doing:

//AppDelegate.h
@interface AppDelegate

@property (strong, nonatomic) MyViewController* myViewDelegate;
@property (strong, nonatomic) MySecondViewController* mySecondViewDelegate;

@end

//MyViewController.m
@interface MyViewController ()

@property (strong,nonatomic) AppDelegate* appDelegate;

@end
@implementation MyViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.appDelegate = (AppDelegate*) [UIApplication sharedApplication].delegate;
    self.appDelegate.myViewDelegate = self; //MySecondViewController would use:
    //self.appDelegate.mySecondViewDelegate = self;
}
...

So two things:

  1. I don't really see a way around declaring new view controllers in the app delegate without using a single root controller that gets assigned on segues, but is having multiple view controller delegates like I'm considered poor design in the first place?
  2. I need a way for ViewDidLoad to call a parent ViewDidLoad to set the value of the app delegate property, as well as the declaration for that app delegate.
Community
  • 1
  • 1
Larry Rubin
  • 123
  • 8
  • 1
    What are you attempting to achieve? This looks (and most likely is) bad design. – Léo Natan Jul 09 '15 at 20:21
  • That was my gut feeling. I'm adding the app delegate to the view controller so I can call a function in the app delegate that touches other classes I'm not importing to the view controller. I was adding the view controllers to the app delegate because that's how I did it in my first project. – Larry Rubin Jul 09 '15 at 20:25
  • You are right, it is a bad design. You don't usually need in your app delegate references to your view controllers. You can access the main window's `rootViewController`, that should be enough. Why were you trying to do this? – Levi Jul 09 '15 at 20:29
  • I originally found it as a solution to another question someone had here with a similar problem I had in my first project. Then I was just mimicking what I did in my first project for this one - I haven't actually found a reason to use it yet. – Larry Rubin Jul 09 '15 at 20:33

0 Answers0