1
votes

I'm pretty new to iPhone development.

I am building an app which has multiple views and controllers. There is only one model.

I need to share the model amongst all of the controllers; so I have instantiated the model inside the App Delegate header file:

@interface MyAppDelegate
(...snip...)
@property (nonatomic, retain) CalcModel *model;

and then synthesized it accordingly.

Inside a controller, I have tried to reference the model like so:

CalcModel* model = [[[UIApplication sharedApplication] delegate] model];

The problem is that the compiler says '-model' not found in protocol

This is probably because the delegate field returns the protocol type, not the concrete MyAppDelegate type... so should I cast [[UIApplication sharedApplication] delegate] to MyAppDelegate, so I can access the model property? If so, how?

Or is this all wrong? More broadly, how would you share a model amongst view controllers?

many thanks for your help

2
I would not recommend putting any data related things into you AppDelegate Class. rather create a Singleton class containing your Datamodel that you can then access easily from all your viewcontrollers. - samsam

2 Answers

0
votes

Yes, just cast it. I #define a macro that wraps this into a simple call to make it easier.

With regard to one way to implement the model structure, there are some useful pointers in this article:

http://www.bit-101.com/blog/?p=1969

(We just implement models as singletons themselves, and use KVO from the views to listen for changes to properties.)

0
votes

You can typecast it just like you typecast any other object

CalcModel* model = (MyAppDelegate *)[[[UIApplication sharedApplication] delegate] model];

you'll have to instanciate the model in you appdelegate .m