Nada
Nada

Reputation: 107

The use of singleton class in objective c and swift

I have a project implemented in both Objective C and Swift classes and I need to have global variables to be shared among these classes . I have two variables currentUsername and currentUsernumber , I need to use these two in each view in the project, what is the best way to implement that ?

I have tried to implement singleton class and here is my code :

    class curentUserSingleton {
static var instance: curentUserSingleton!
var currentUsername: String = ""
var currentUsernumber: String = ""

// SHARED INSTANCE
class func sharedInstance(Name : String , Number : String) -> curentUserSingleton {
    self.instance = (self.instance ?? curentUserSingleton(uName: Name , uNumber: Number))
    return self.instance
}

// METHODS
init(uName : String , uNumber : String) {
    self.currentUsername = uName
    self.currentUsernumber = uNumber
}}

But I don't know how to use this class safely in the OC and Swift and I am a little confused since I get declaration errors when I use the class in my code! Is this the right way to write a singleton class and how to call it in both languages ?

Upvotes: 1

Views: 1865

Answers (2)

Rob
Rob

Reputation: 437532

I'd be inclined to do something like:

class User: NSObject {
    static let sharedInstance = User()

    var name: String?
    var number: String?
}

Then you can set and retrieve name and number like so in Swift:

User.sharedInstance.name = "Foo"
User.sharedInstance.number = "42"

print(User.sharedInstance.name)
print(User.sharedInstance.number)

Obviously, to access this from Objective-C .m file, you have to have to include the system generated header like so:

#import "ModuleName-Swift.h"    // obviously, replace `ModuleName` with the name of your module

But then the syntax for setting and retrieving these properties is similar as it was in Swift:

[User sharedInstance].name = @"Foo";
[User sharedInstance].number = @"42";

NSLog(@"%@", [User sharedInstance].name);
NSLog(@"%@", [User sharedInstance].number);

Upvotes: 1

pco494
pco494

Reputation: 371

To me it seems you do not need a singleton at all. I suggest you would be best of redesigning the architecture to have a user class that can store the information you are needing (and more if you finds the need in the future).

Then you could either pass that user object around between the view controllers as they need or perhaps easier define a currentUser property for the app delegate class.

That way each view controller can obtain the app delegate from the NSApp global reference to the application object and then get the current user object from there. With this pattern the app delegate acts as the globally accessible singleton you need without any need to manage it yourself.

Upvotes: 0

Related Questions