denislexic
denislexic

Reputation: 11352

How to store objects in memory

I come from JavaScript and I'm used to fetching data through an API once and then using it throughout the app (as long as I don't need to do a page reload). For example, if I write var user = $.get('/get/user'), I can then use the user variable everywhere, even if I load a new view/page.

As I understand it, each View Controller is like a new page. Therefore, how can I get, for example, my user when the app starts and use it throughout the app without storing it in Core Data or somewhere similar?

Can I instantiate a class when the application starts that gets all the initial values and then stores them for use everywhere? If so, how?

Upvotes: 1

Views: 1543

Answers (1)

Tim
Tim

Reputation: 9042

You can follow the singleton pattern. This is an object that holds a static reference to itself and this instance is accessed using a class method.

class YourSingletonClass {
    static let sharedInstance = YourSingletonClass()

    func someMethod() -> Void {

    }
}

// Other part of the app

YourSingletonClass.sharedInstance.someMethod()

The other approach is to create an object (instance of a class), populate the variables with the data you require to persist in memory and then pass this instance from View Controller to View Controller.

var myVar = YourClassForMemory()

myVar.value = 1
myVar.otherValue = 2

You can then create a property on other View Controllers of type YourClassForMemory, and set it with this object when you initialise the View Controller and pass the object around. This can be done in prepareForSegue, if using Storyboard segues, or as an init method, or just a public property on the class.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "mySegue" {

        var myVar = YourClassForMemory()

        myVar.value = 1
        myVar.otherValue = 2

        (segue.destinationViewController as! SomeViewController).myVar = myVar
    }
}

Upvotes: 2

Related Questions