Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>// See Mike Ash "Care and Feeding of Singletons" // See Cocoa Samurai "Singletons: You're doing them wrong" +(MySingleton *)singleton { static dispatch_once_t pred; static MySingleton *shared = nil; dispatch_once(&amp;pred, ^{ shared = [[MySingleton alloc] init]; shared.someIvar = @"blah"; }); return shared; } </code></pre> <p>Be aware that <a href="https://stackoverflow.com/a/7997698/412916">dispatch_once is not reentrant</a>, so calling itself from inside the dispatch_once block will deadlock the program.</p> <p>Don't try to code defensively against yourself. If you are not coding a framework, treat your class as normal then stick the singleton idiom above. Think of the singleton idiom as a convenience method, not as a defining trait of your class. You want to treat your class as a normal class during unit testing, so it's OK to leave an accessible constructor. </p> <p>Don't bother using <code>allocWithZone:</code></p> <ul> <li>It ignores its argument and behaves exactly like <code>alloc</code>. Memory zones are no longer used in Objective-C so <code>allocWithZone:</code> is only kept for compatibility with old code. </li> <li>It doesn't work. You can't enforce singleton behavior in Objective-C because more instances can always be created using <code>NSAllocateObject()</code> and <code>class_createInstance()</code>. </li> </ul> <p>A singleton factory method always returns one of these three types:</p> <ul> <li><code>id</code> to indicate the return type is not fully known (case where you are building a class cluster).</li> <li><code>instancetype</code> to indicate that the type returned is an instance of the enclosing class. </li> <li>The class name itself (<code>MySingleton</code> in the example) to keep it simple.</li> </ul> <p>Since you tagged this iOS, an alternative to a singleton is saving the ivar to the app delegate and then using a convenience macro that you can redefine if you change your mind:</p> <pre><code>#define coreDataManager() \ ((AppDelegate*)[[UIApplication sharedApplication] delegate]).coreDataManager </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload