Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are several reasons that Cocoa encourages the use of <code>[Foo sharedFoo]</code> rather than a global Foo object.</p> <p>[Foo sharedFoo] can auto-instantiate the first time it's used.</p> <p>Naming the instance with a capital letter is very confusing because it looks like a class, encouraging bugs. Consistency in naming is at the heart of good Objective-C. The compiler cannot protect you against a wide variety of mistakes because ObjC is highly dynamic. Good naming and self-discipline in consistency is what leads to bug-free Cocoa.</p> <p>Parallelism:</p> <pre><code>Foo *foo = [Foo sharedFoo]; Foo *foo = [[[Foo alloc] init] autorelease]; Foo *foo = [Bar fooAtIndex:0]; </code></pre> <p>All three of those may be legal in the same program. Just because there is a singleton instance doesn't mean that there aren't other instances, too. NSNotificationCenter is a good example of this. It's a singleton, but you can make additional instances (and there are reasons to do so).</p> <p>A global variable can be globally modified. A <code>sharedInstance</code> cannot be. For instance, if <code>State</code> is a global variable (rather than a class), then <code>State=nil</code> is legal anywhere in the program. That breaks encapsulation and is an easy typo for <code>state=nil</code> that cannot be caught by the compiler. If <code>State</code> is a class, then the compiler can catch this easy error.</p> <p>The many rules of Cocoa naming are there to encourage highly readable code, and to minimize bugs in a highly dynamic and loosely typed environment. Like Perl's <code>use strict</code> we should be very careful before giving up what little safety net we have.</p>
 

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