objective c - Is this valid code to create a NIB-instantiated singleton? -


Assume that I institute an object of class MyGreatClass in my NIB (normally by dragging "object" to NIB and Sets its class in MyGreatClass).

I would like to reach that example anywhere in my codebase, without the introduction of coupling, i.e., like crazy objects without misleading objects, and without any outlet, [NSASP representative]. (Adjustable too heavily with later time.)

I ask: Is it considered to be a good code to complete?

  // Import static MyGreatClass * theInstance = zero; @Employment MyGreatClass + (MyGreatClass *) Shared Instruction {NSAssert (Instance! = Zero, @ "Example should have been loaded by NIB"); Instant return; } - Wake up from (id) init // NIB will call it {if (! Instance) instance = self; Instant return; } // ...   

If this work is expected, I will be able to get my example through shared interaction after the app loads.

What do you think? Update: Hmm, on the second thought, the above init method is perhaps the easiest way to think about it:

  - (id) init {NSAssert (! TheInstance, @ "The example should not exist because the NIB-awakening process is simply called" @ "); Instant = self; Instant return; }   

Then, what do you think?

The way to create a proper singleton is to override allocWithZone: so that it To be sure that another object can not be created. Overriding allows init to create new objects, but not initialized. It is thrown away because the init method only ignores it and returns the object that is already made. Here's how I can do this:

  + (MyGreatClass *) Shared Instance {NSAArt (instance! = Zero, @ "Example should have been made by NIB"); Instant return; } + (MyGreatClass *) allocWithZone: (NSZone *) area {if (instance) returns the intern; Return [in-your-self] init]; } - (id) Init {If (The Instance) returns the intern; If (self = [super init]) {instance = self; // other initialization} returns self; } - (zero) release {} - (zero) DLOK {return; [Super DeLoc]; // Stop the warning to warn the compiler to super-call}   

I have to overload the release and dealloc I'm doing that, so that the singleton will not be deallocated. If you do not do this, you should put it in the shared instance method and resume it automatically. If you want to support multithreading, you should synchronize access to the theInstance variable.

Comments