Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it common/ok to declare global class instances in Swift/iOS

I recently watched a video tutorial in Lynda.com and I noticed that the author declared a few global variables which included two class instances. The main reason for my question is because I have heard that we need to try to avoid using global variables unless your really need them. I can see using global variables for NSUserDefaults' Keys but I'm not sure about global instances.

Here is the code showing the global variables declarations. I'm only concerned about variables masterView and detailViewController.

import UIKit

var objects:[String] = [String]()
var currentIndex:Int = 0

var masterView:MasterViewController?
var detailViewController:DetailViewController?

let kNotes:String = "notes"
let BLANK_NOTE:String = "(New Note)"

class MasterViewController: UITableViewController {

     // class code 

}

Is it ok to declare your class instances as global variables?

like image 392
fs_tigre Avatar asked Mar 13 '23 16:03

fs_tigre


2 Answers

It is certainly OK to use global variables in your Swift code from the technical point of view, in the sense that your program is not going to crash or otherwise "misbehave" because of that. When you are building a quick example for a demonstration, global variables provide a convenient way to shorten the code.

However, there are drawbacks to using mutable global variables that makes their use questionable. Specifically, they break encapsulation. Looking at the code that you provided, two variables

var objects:[String] = [String]()
var currentIndex:Int = 0

should be hidden in a model object, over which you have some degree of control.

Using globals may produce some unexpected behavior if you are not careful about clearing them. For example

var masterView:MasterViewController?
var detailViewController:DetailViewController?

may retain references to view controllers that are no longer visible.

like image 165
Sergey Kalinichenko Avatar answered Mar 16 '23 04:03

Sergey Kalinichenko


That's okay to declare a class instances as a global variable, if you want to prefer use of only one instance of that class through out your app work.
NOTE: you can hide those properties & functions of that instance by making those Private, which you don't want to be accessed by global instance variable.

like image 30
Kiran Jasvanee Avatar answered Mar 16 '23 04:03

Kiran Jasvanee