magiclantern
magiclantern

Reputation: 798

How to access properties on AppDelegate from classes owned by it?

I'm writing a simple OS X app which so far is structured like so:

I sometimes need to access properties on AppDelegate from the ViewControllers, which I'm doing like this:

AppDelegate *delegate = (AppDelegate *)[[NSApplication sharedApplication] delegate];
delegate.someProperty = someValue;

This "feels" hacky. Is it a proper pattern or is this really dumb?

Two alternative architectures I came up with were:

  1. To use delegation and define some kind of "UI Delegate" protocol in the VCs and make the AppDelegate conform to it
  2. To have the VCs post notifications that the AppDelegate listens to

The first feels tangled and dirty, the second feels unreliable.

What is the proper pattern here? How should VCs owned by the AppDelegate access its properties?

Upvotes: 0

Views: 434

Answers (2)

CatVsDogs
CatVsDogs

Reputation: 374

Try this

AppDelegate *app = [NSApp delegate];

Instead of this

AppDelegate *delegate = (AppDelegate *)[[NSApplication sharedApplication] delegate];

Upvotes: 1

Fruity Geek
Fruity Geek

Reputation: 7381

You can define a category on NSObject that will allow you to get your instance of the AppDelegate from any object in your project.

@interface NSObject (AppDelegate)

- (AppDelegate *)appDelegate;

@end

You can then include the category in your project .pch file so that it's available everywhere.

Upvotes: 0

Related Questions