0

I have an singleton class with set of properties where I will store some global values that can be used across project.

In a place I am in a need of class with same property as singleton class. So my question is is this a right way I can use my same singleton class as private.?

let medicine1 = Medicine.sharedInstance()
medicine1.frequency = 2
print("medicine1 \(medicine1)")
print("medicine1.frequency: \(medicine1.frequency)")

        let medicine2 = Medicine()
        medicine2.frequency = 4
        print("medicine2 \(medicine2)")
        print("medicine2.frequency: \(medicine2.frequency)")
        print("medicine1.frequency: \(medicine1.frequency)")
nik
  • 2,289
  • 6
  • 37
  • 60
  • 2
    It looks like `Medicine` shouldn't be a singleton. – Paulw11 Aug 05 '16 at 13:09
  • Unfortunately, the term "singleton" is often used for what is in fact a "shared instance". – Martin R Aug 05 '16 at 13:10
  • It should be workable, though, like others, I wouldn't call it a singleton. Consider NSNotificationCenter from the SDK. The docs say, "You typically don’t create your own"...but there's no singleton guarantee, just a usual default. – Phillip Mills Aug 05 '16 at 13:13
  • Anyway separate instance of singleton will never affect the actual singleton values right ? – nik Aug 05 '16 at 13:18
  • 1
    @nik With a true singleton, there's no such thing as "separate instance of singleton", that's the whole point: having one single, *unique* instance shared for all the code. If it's not a unique shared instance it is not a singleton, it is just a shared object. – Eric Aya Aug 05 '16 at 15:01
  • @EricAya My point here is not creating a separate instance of singleton class. My question here was Is it I can reuse the singleton class(i.e class and its properties) to store another object's value – nik Aug 08 '16 at 07:39
  • Check my code above sharedInstance() will return same object gain and again which nothing but singleton. And Medicine() is an another object of medicine class. Am i doing right is what my question here – nik Aug 08 '16 at 08:21
  • 1
    If you're able to make a new instance of `Medicine` then `Medecine` is not a singleton. Only the `sharedInstance` should be available. Have a look here: http://stackoverflow.com/a/36012158/2227743 -- If you need/want this other instance, then you should *not* make `Medecine` a singleton. It's one way or the other, not both. – Eric Aya Aug 08 '16 at 09:10
  • 1
    You should also read this recent one: http://stackoverflow.com/q/38819314/2227743 – Eric Aya Aug 08 '16 at 10:47
  • @EricAya Thanks for clarification – nik Aug 08 '16 at 10:49

0 Answers0