Graphics Programs Reference
In-Depth Information
jects will talk to. Those objects can ask the singleton class for its one instance, which is
better than passing that instance as an argument to every method that will use it.
To get the (single instance of)
BNRItemStore
, you will send the
BNRItemStore
class the message
sharedStore
. Declare this class method in
BNRItemStore.h
.
#import <Foundation/Foundation.h>
@interface BNRItemStore : NSObject
{
}
// Notice that this is a class method and prefixed with a + instead of a -
+ (BNRItemStore *)sharedStore;
@end
When this message is sent to the
BNRItemStore
class, the class will check to see if the
single instance of
BNRItemStore
has already been created. If it has, the class will re-
turn the instance. If not, it will create the instance and return it. In
BNRItemStore.m
,
implement
sharedStore
.
+ (BNRItemStore *)sharedStore
{
static BNRItemStore *sharedStore = nil;
if (!sharedStore)
sharedStore = [[super allocWithZone:nil] init];
return sharedStore;
}
Notice that the variable
sharedStore
is declared as
static
. Unlike a local variable, a
static variable
does not live on the stack and is not destroyed when the method returns. In-
stead, a static variable is only declared once (when the application is loaded into
memory), and it is never destroyed. A
static variable
is like a local variable in that you
can only access this variable in the method in which it is declared. Therefore, no other ob-
ject or method can use the
BNRItemStore
pointed to by this variable except via the
sharedStore
method.
The initial value of
sharedStore
is
nil
. The first time this method runs, an instance
of
BNRItemStore
will be created, and
sharedStore
will be set to point to it. In sub-
sequent calls to this method,
sharedStore
will still point at that instance of
BNRItemStore
. This variable has a strong reference to the
BNRItemStore
and, since
this variable will never be destroyed, the object it points to will never be destroyed either.
To enforce the singleton status of
BNRItemStore
, you must ensure that another in-
stance of
BNRItemStore
cannot be allocated. One approach would be to override
al-