I am working on an ios app in which in the first viewcontroller the user is asked to provide its name gender age and native language. Then i will use those objects during the whole app. So what is the best way to store the objects so they are easilly accessible from all classes?
Create singleton class say MySingletonClass and define your variable. you can access your variable from any class by singleton object.
// MySingleton.h
@interface MySingletonClass : NSObject
{
//your global variable here
}
// set property for your variable
+ (MySingletonClass*)sharedInstance; // method for getting object of this singleton class
// In MySingleton.m
//synthesize property for your global variable
+ (MySingletonClass*)sharedInstance
{
if ( !sharedInstance)
{
sharedInstance = [[UIController alloc] init];
}
return sharedInstance;
}
Now in other class you can access this variable. follow this code to access variable define in MySingletonClass
MySingletonClass* sharedInstance = [MySingletonClass sharedInstance]; // get object of MySingletonClass
sharedInstance.yourVariable; // now you can access variable defined in MySingletonClass by this object.
You can also definde global variable in AppDelegate (not recommended ).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With