0

I was trying something new so just going through a thought process to allow only my singleton class to create new instance for other classes which are hidden behind it.

I am able to restrict to call the init method using the "unavailable" attribute along with my init method but can I create an exception that only my Singleton class can call the init method.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Akhilesh Sharma
  • 1,580
  • 1
  • 17
  • 29

1 Answers1

1

but can I create an exception that only my Singleton class can call the init method

You can't know who the caller is — see this discussion of the matter — but you can certainly hide the init method by not putting it in your header. A commonly used solution is, if possible, to have the singleton factory method call a "private" initializer and throw an exception on the "public" initializer. Of course that doesn't ultimately prevent anyone from calling the "private" initializer - sorry, Objective-C is too dynamic for that - but it makes it harder to obtain a non-singleton instance by mistake.

Community
  • 1
  • 1
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Thanks Matt. Ya i might need to think about some other solution but still wanna find out to what extent I can go.. – Akhilesh Sharma May 12 '15 at 18:10
  • The first solution here is what I use: http://stackoverflow.com/a/7035136/341994 But again I would emphasize that you are just rearranging the deck chairs on the Titanic: the "private" initializer is not really private in Objective-C. You are programming by contract, not by enforcement. – matt May 12 '15 at 18:14
  • I would say that its not a duplicate matt. The one question that you have linked to is the question that how to have private methods.. I already know that how I can enforce this but my question is there a way where we can have an exception for classes like a specific list who can instantiate an object. – Akhilesh Sharma May 12 '15 at 18:16
  • And I told you you couldn't. So the question is answered coming from both directions. If that were possible, it would have been suggested among the answers in the other question anyway. – matt May 12 '15 at 18:17
  • Then I preassume that its not a duplicate but its a feature that is restricted in objective c – Akhilesh Sharma May 12 '15 at 18:19
  • Could have called it a duplicate of this, which is definitely answered by someone deep inside Apple: http://stackoverflow.com/questions/1793999/how-to-find-out-who-called-a-method Whatever. – matt May 12 '15 at 18:51
  • Matt.. This something we cannot say whether its a duplicate or not with the one marked above.. But I already checked all these answers before posting it here. And my question is pretty much in a different context. – Akhilesh Sharma May 12 '15 at 18:55