Easy implementation of using singleton in Objective-C/Swift

Singleton: Instantiation of a class to one object

Features of Singleton:

  1. One class only can have only one instance;
  2. It must can create this instance automatically;
  3. This instance must be provided to other objects.

Benefits of Singleton:

All objects can only have one instance. In other words, all the instances, no matter how they were created, they have the same memory address. In practise, we want singleton class to manage our database read/write, file IO, to make sure the data integrity.

As we know, there are three Options to create an instance:

Option 1. using alloc and init
Option 2. using static method. A way such as [UIApplication sharedApplication] to create a new instance.
Option 3. copying from an existing object

For example, create a custom class named Item, and implement its singleton method as:

In the code:

  • Remember copyWithZone method must be override when you want to do the copy on object
  • allocWithZone is called when you create an instance by alloc and init
  • When you are using multi-threading, singleton instance should be avoided created multiple times.

Another way for you to create a singleton is using use GCD:

Updated: Singleton in Swift 2/3/4/5

class SingletonA {    static let sharedInstance = SingletonA()    init() {
println("AAA");
}
}

Updated in 2020: How to destroy a singleton object

In a recent project, I was trying to reload the whole application when a game is finished. (Yes, it is using the Spritekit!), and there is a need to manually dispose the singleton object while reloading. I tried many ways but find the following working pretty well:

class SoundManager: NSObject {

struct Static {
static var instance: SoundManager?
}

class var shared: SoundManager {
if Static.instance == nil {
Static.instance = SoundManager()
}
return Static.instance!
}
}

So whenever you want to destroy a singleton, you can call it by:

SoundManager.Static.instance = nil

Reference:

--

--

--

needone.app

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

AppSync Unified 102.0 update added support for latest iOS 14.8

Check Internet Connectivity with NWPathMonitor In Swift

How to save checkbox state in a recylerview

Dynamic List and Identifiable in SwiftUI

Combine Framework-Part 5

Cloning Tinder With SwiftUI

A journey towards Apple’s Exposure Notification Framework and how to use it

Segues + @IBAction Functions = Trouble

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Needone App

Needone App

needone.app

More from Medium

What is the Variables and Constants in Swift Language ?

Test Double : Stub

Getting Familiar with a New Code Base — A Beginner’s Guide

How to Intercept Http requests in Charles proxy for iPhone