Singleton Overlaps? - ios

I have two classes using as singletons.
class Boss {
static let sharedInstance = Boss()
private init() {}
var user_id : String?
var username : String?
}
class Job {
static let sharedInstance = Job()
private init() {}
var job_id : String?
var JobType : String?
}
But after populating the Boss.sharedInstance first, Job.sharedInstance also containing Boss' class variables. But after replacing the sharedInstance with other name (for eg. job_sharedInstance and boss_sharedInstance) respectively, things are working fine. It's quite weird. Can anybody explain me the reason why it would happen like this. Thanks in advance.
Here is the breakpoint. Although Job.sharedInstance does not have user_id, username, etc..., it's showing up.

There is no problem with your code. Both Boss and Job
have a static let sharedInstance property, and these are
completely independent of each other. Different classes
can have static properties with the same name,
and these don't "overlap".
If the debugger shows properties for Job.sharedInstance
which are not even defined in the Job class then this is
a bug in the debugger view.
When in doubt, add print statements to your code.

Related

Swift singleton not accessible from within function

I'm trying to access a singleton value that is accessible throughout my application apart from one function. I can get the value at either end of the function however inside the function it can't be accessed. To confirm I have set these values so they are not empty.
My singleton is declared as follows:
var customer: Customer = Customer.sharedInstance
final class Customer {
static let sharedInstance = Customer()
var name: String!
var address: String!
var zipcode: String!
var id: String!
private init() {}
}
I can access any of these values from within viewDidLoad and other methods apart from one which is below:
fileprivate func processCustomer() {
... Do logic here
print(customer.name) // Print's out nil
... perform closure method
... print(customer.name) // Print's nil
}
Any ideas as I've rewritten it twice already. I've also removed fileprivate and renaming the function. It's almost as if the function can't read the value of a singleton more than once??
Thanks

Singleton and Class Properties in Swift

I am trying to create a singleton class. For this I have tried to use two different approaches i.e.
1.First approach - Employee class contains two instance properties, a class property that contains the shared instance of the class and a private initializer, i.e.
class Employee
{
var firstName : String
var lastName : String
static let sharedInstance = Employee(firstName: "Payal", lastName: "Gupta")
private init(firstName : String, lastName : String)
{
self.firstName = firstName
self.lastName = lastName
}
}
2.Second approach - Employee2 class contains two class properties, i.e.
class Employee2
{
static var firstName : String = "SomeFirsrName"
static var lastName : String = "SomeLastName"
}
Are these two approaches of making the singleton equivalent? If yes, which one should I use and what are the differences between each of them in respect of singleton?
To make a simple singletone class in Swift you could write:
class SomeManager {
static let sharedInstance = SomeManager()
}
Usage:
SomeManager.sharedInstance
What does it mean?
Since Swift 1.2 it's possible do declare static class properties. So you can implement the singleton like this. There can only be one instance for the lifetime of the application it exists in. Singletons exist to give us singular global state.
The first approach create a singletone having a class with this initialization: Employee(firstName: "Payal", lastName: "Gupta")
The second approach don't create a singletone, is a simple class with two static declared properties.
These two approaches are not equivalent:
The first approach creates an instance of Employee object
The second approach defines two class fields; it does not create any object instances.
In other words, only the first approach creates a singleton. The second approach makes a collection of related fields at the class level.
Try this...
class Employee : NSObject
{
var firstName : String
var lastName : String
class var sharedInstance: Employee {
struct Static {
static let instance: Employee = Employee(firstName: "Payal", lastName: "Gupta")
}
return Static.instance
}
private init(firstName : String, lastName : String)
{
self.firstName = firstName
self.lastName = lastName
}
}

How to create struct data globally accessible in a singleton class in swift 2.0 (iOS)?

I'm very new to iOS programming and swift. I am trying to create a singleton class to store my global data. My global data are a struct and an array of this struct. I want to have only one instance of this class, thus a singleton class. Global data should be accessible and editable to all ViewControllers. I have been searching around and I almost have it figured out except one last part. Here is the singleton class:
import Foundations
class Global {
struct Info {
var firstname:String!
var lastname:String!
var status:String!
init (firstname:String, lastname:String, status:String)
{
self.firstname=firstname
self.lastname=lastname
self.status=status
}
}
var testString: String="Test" //for debugging
var member:[Info]=[]
class var SharedGlobal:Global
{
struct Static
{static let instance = Global()}
return Static.instance
}
}
Now I want to access the global variables of this singleton class from some viewControllers. When I type this in xcode:
Global.SharedGlobal.
I get two options one is the array member and the other is the testString. The struct Info is not available. However, if I just type
Global.
then I see Global.Info and Global.SharedGlobal as my options.
Why is that I can't access the struct in my singleton class (i.e. Global.SharedGlobal.Info)? I am missing something? I appreciate any feedback or help. Thanks a lot in advance.
Unless there's a very specific reason to do it, you don't need to nest classes like that.
Let's simplify a bit your code for the exercise:
struct Info {
// No need for these properties to be Implicitly Unwrapped Optionals since you initialize all of them
var firstname: String
var lastname: String
var status: String
init (firstname:String, lastname:String, status:String) {
self.firstname=firstname
self.lastname=lastname
self.status=status
}
}
class Global {
// Now Global.sharedGlobal is your singleton, no need to use nested or other classes
static let sharedGlobal = Global()
var testString: String="Test" //for debugging
var member:[Info] = []
}
// Use the singleton like this
let singleton = Global.sharedGlobal
// Let's create an instance of the info struct
let infoJane = Info(firstname: "Jane", lastname: "Doe", status: "some status")
// Add the struct instance to your array in the singleton
singleton.member.append(infoJane)
Now it would make sense to me. A struct holding info about some user, and I can make any number instances of them - and a singleton class, unique, were I can store these Info instances, this singleton being usable anywhere.
Is it the kind of thing you wanted to achieve?

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 ?
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);
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.

How to create singleton with parameter in swift:

I have the following class:
class FeedDataManager: URLManagerdelegate {
let TAG: String = "FeedDataManager"
weak var mDelegate: KeyboardViewController?
var mModelManager: ModelManager!
var mURLManager: UrlManager!
var mGetNewsTimer: NSTimer?
var mFeedsArray: Array<News>!
var mManagedObjectContext: NSManagedObjectContext!
var mPersistentStoreCoordinator: NSPersistentStoreCoordinator!
var mManagedObjectModel: NSManagedObjectModel!
class var sharedInstance: FeedDataManager {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: FeedDataManager? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = FeedDataManager()
}
return Static.instance!
}
init (aDelegate: KeyboardViewController) {
self.mDelegate = aDelegate
}
}
The Problem: If you look at the init method you will see that it should receive as a parameter a delegate pointer that I want to store in the singleton, so basically I need to pass this parameter to this line:
Static.instance = FeedDataManager()
But I have no idea how it's done, Does any knows how this can be done?
BTW: I saw this link:
Singleton and init with parameter
But the singleton creation there is different.
We can show you how you can add parameter to declaration of singleton, but that's not really a good idea. The entire idea behind a singleton is that it doesn't matter where it is instantiated, you can use it anywhere. What does it mean if you invoked this singleton in two different places in your code, with different parameters? You have a race condition, where the behavior may change depending upon where and how the singleton was first encountered.
Unrelated, but the dispatch_once is redundant. The static variables are already employed with dispatch_once. See discussion at end of http://developer.apple.com/swift/blog/?id=7 (this is primarily geared towards globals, but as they parenthetically point out, it applies to static variables, too). Also, in Swift 1.2, we can now have static class variables, eliminating the need for the struct, too

Resources