sharing an object between two viewcontrollers in objective c
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 t开发者_C百科hat?
Thank you much all.
You might consider adding a @property
to both view controller's that points to your model ("engine") object. When the view controller's are created, you can set that @property
to point to the model. If the @property
is retain
, then it won't copy the model.
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.
Since you only have one of these "Engines", I'd suggest going the singleton route.
Create a static method that returns an instance to the object you want shared, then you can use that method in each class.
forgive my syntax... I don't have my objective C stuff in front of me atm, but essentially you'll want to do something like the following.
EngineClass.h file:
STATIC EngineClass * getSingleton();
STATIC EngineClass * INSTANCE;
EngineClass.m file:
STATIC EngineClass * getSingleton()
{
if(INSTANCE == null)
{
INSTANCE = new EngineClass();
}
return INSTANCE;
}
精彩评论