Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Singleton class in Swift

    • 0
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 483
    Comment on it

    Hello reader's !

    The singleton class ,which is responsible to instantiate itself, to make sure it creates not more than one instance, in the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere using its sharedInstance() method , being impossible to invoke directly the constructor each time.

    for example , DataObjects.swift is a singleton class

    import UIKit
    
    class DataObjects: NSObject {
    
    
        class var sharedInstance :DataObjects {
            struct Singleton {
                static let instance = DataObjects()
            }
    
            return Singleton.instance
        }
    }
    

    Store global variable If you want to use a variable global to application then just add AnyObject variable in class as shown :-

    import UIKit
    
    class DataObjects: NSObject {
    
        var userIdentity:AnyObject!
    
        class var sharedInstance :DataObjects {
            struct Singleton {
                static let instance = DataObjects()
            }
    
            return Singleton.instance
        }
    } 
    

    Now you can use this variable as shown :-

    DataObjects.sharedInstance.userIdentity = "commonMan"
    

    Thanks Readers.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: