Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing global objects in IOS apps?

Tags:

ios

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?

like image 295
Tiko Harutyunyan Avatar asked Jan 12 '23 13:01

Tiko Harutyunyan


1 Answers

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 ).

like image 139
Mayank Jain Avatar answered Jan 21 '23 06:01

Mayank Jain