Reputation: 5698
Say I have an NSWindowController
subclass: MyWindowController
.
For this class, I have a singleton instance, sharedWindowController
Inside of my implementation of MyWindowController
, within my methods should I be referencing self
or [MyWindowController sharedWindowController]
?
In a normal subclass the answer would be self
; but I am looking at some legacy code in my codebase, and the previous author has been referencing [MyWindowController sharedWindowController]
. I'm assuming this is because in theory there will only ever be one instance of MyWindowController
, so by referencing sharedWindowController
, we are just being safe?
But is this unnecessary?
Upvotes: 1
Views: 53
Reputation: 52538
Either there is only one, then [SomeClass sharedThingy] and self refer to the same object, but self is much faster and much less code to write.
Or there is more than one, then self is still faster and much less code to write, but it refers to the right object.
In each case, better to refer to self.
On top of that, [SomeClass sharedThingy] will create a deadlock on the first call with some bad luck (if anything referred to in the allocation code uses [SomeClass sharedThingy]).
Upvotes: 0
Reputation: 53000
It is both unnecessary and bad.
in theory there only ever will be one
From the description you have a shared instance model, not a singleton model, there could be more than one. Debugging would get messy quickly due to unexpected object interactions.
And while not significant the code is also larger and slower.
So the code takes a risk, introduces potential bugs, and all for no gain.
Upvotes: 2