I am guessing that this maybe a silly beginner question, but I cant figure out the answer to it. I basically have two view controllers in my iphone app that I would like them to share a third class (.m and .h) that suppose to hold data that both suppose to use. Lets say for example that both views are displaying locations and presenting a table with some of this information manipulated – what i’d like to do is to have a third class, like an engine, that will do all that, and those views will just instantiate this engine and read the table/location data when needed.
My question is – how can I instantiate this engine in both my views but have in fact only one copy of the engine that both views read from. I know that when instantiating twice, two copies are being created, and i dont want that. i am hoping to make this engine “global”.
is this possible at all in objective c? what would be the best way to go about that?
Thank you much all.
You have a lot of options when it comes to this. Following an MVC approach, you are on the right track in that you should have a single copy of this data (the model). How you get that to your view controllers is up to you. I’ll give two ways and you can see which works better in your situation, but there more than ways to do this. Option 1) Create a singleton to house your model/data. You’ve probably seen this in the SDK when using stuff like … = [SomeController sharedInstance]. The two view controllers can just use that shared instace. Option 2) You can instantiate the model somewhere at startup and pass it directly to the view controllers. Whether it’s a singleton or not is not their concern. They just know they have access to some data. You can create a property like @property (nonatomic, retain) TheData *theData for each of the view controllers and pass it that way.