Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About Global variable for iOS Project

I would like to know how to use Global variable for iOS Project.

Nowadays, I found one document which is writtern by Swift.

This document has some code.

import UIKit

let log = ColorLogger.defaultInstance

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

      var window: UIWindow?


      func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

This program has only global variablesn which is log.

log is usually used for development,not production.

I think log should be inside appdelegate.

But i don know standard about how to handle variables for iOS Project.

Is using global variables standard for iOS product?

like image 902
shunsuke_stackoverflow Avatar asked Jun 10 '16 08:06

shunsuke_stackoverflow


1 Answers

There are several ways to create "global" variables in Swift, and I will describe some of them.

1. Defining variables in AppDelegate

AppDelegate seems like a logic place for some global variables. As you said you can create instance of logger or create instance of something else in AppDelegate.

To create instance which will be used as a global variable go to the AppDelegate.swift and create the variable like this:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
...
    let myAppInstance = SomeClass()
...
}

Then, if you want to access myAppInstance in any other part of the application you would write:

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.myAppInstance.doSomething()

2. Creating singletons

Singletons are probably one of the most used design patters used through any Apple platform. They are present in almost any iOS API you are using when creating application, and they are commonly used to create global variables.

Essentially, singletons are lazy-loaded instances which are only created once. Let's look at the code example:

class MyDataStructure {
   static var sharedInstance = MyDataStructure() // This is singleton

   private init() {

   }
}

We have created the class MyDataStructure and the singleton instance named sharedInstance. This is the most common name for the singletons since that singletons are shared instances through the app.

Note the use of the static keyword when defining singleton. static keyword tells the compiler to create sharedInstance only the first time it is being accessed. Any other access to the sharedInstance will just reuse instance that is created first time.

To use it you would just write:

MyDataStructure.sharedInstance
like image 143
Said Sikira Avatar answered Oct 07 '22 00:10

Said Sikira