0

Currently I have 2 ViewController files I want to share common data between, however I want to have a class called GlobalVariables store all of the variables throughout my code. In one of the ViewController files, I want to set the value of a variable (I have created a setVariable method in the GlobalVariables.m file) and from the ViewController, I want to call this method so it sets the variable. How can I do this without creating an instance of GlobalVariables as any changes I make to the instance will not carry over when I create another instance of GlobalVariables in my second ViewController file?

1
  • Do some searching on "singleton". Commented Jan 30, 2014 at 5:27

3 Answers 3

2

Use singleton Design Pattern. It’s an extremely powerful way to share data between different parts of code without having to pass the data around manually. And also it will always be a single instance through out the Application life cycle

Please check this link: Singleton Class

Sign up to request clarification or add additional context in comments.

2 Comments

The singleton design pattern worked great for accomplishing this task!
@Mayankmmmx: If my ans you then accept my ans so that it also helpful for others. Thanks
0

Define your varible in AppDelegate. AppDelegate is a Singleton class. And access that variable where you want.

3 Comments

I'm just letting you know that this method could get you some serious backlash! The app delegate should not be used like this. I remember in my good ole days where I suggested methods like this and got whipped for it by the stack community! Just giving you a heads up :)
hey can you tell me if i want access appdelegate method than how can i call them
Agreed. Do NOT use the app delegate as a dumping ground for globals.
0

It's unclear what you mean by "set values to a class". There are 3 kinds of variables in Objective-C: global variables, instance variables, and local variables. Local variables are not relevant. If you con't want to create an instance, then instance variables are out. So then you want global variables. They can be set and accessed by any function or method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.