[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: sync.m

From: Richard Frith-Macdonald
Subject: Re: sync.m
Date: Sun, 28 Feb 2010 09:30:30 +0000

On 28 Feb 2010, at 08:42, address@hidden wrote:

>> Although this works, it is a really, really bad way of creating a singleton.
> I copied it from the apple developer pages...


> I thought +initialize would be called on program startup for every
> class.

I guess you are confusing +initialize with +load

The +load method is called when your code is loaded into the program (usually 
on program startup unless your code is in a dynamically loaded bundle)
The +initialize method is called the first time anything tries to *use* the 

> I want to be able to create my singleton on demand since it has
> a rather large memory footprint. If that works with the method you
> propose I'm fine with it.

+initialize is perfect for that.

>> Your +allocWithZone: method should really check that it's not a
>> subclass, before returning the singleton.
> I don't want this class to be subclassed.

All the more reason why you should check.
+ (id) allocWithZone: (NSZone*)z
  if (self != [MyClass class])
      []NSException raise: NSInvalidArgumentException
                              format: @"Illegal attempt to subclass MyClass as 
%@", self];
  if (sharedInstance == nil)
      sharedInstance = [super allocWithZone: z];

>> In -initWithName:, you should check that self != nil after [super
>> init].  See the SUPERINIT macro from EtoileFoundation.
>> In a singleton, it's a good idea to override -dealloc to not call
>> [super dealloc].  This will cause a warning with GCC, which you can
>> hide like this:
>> - (void)dealloc
>> {
>>      if (0)
>>      {
>>              [super dealloc];
>>      }
>> }
> How would you deallocate your singleton then?

Typically you don't deallocate singletons ... the idea is that they are created 
on demand and then are available for the rest of the program.
If you *want* to manually destroy the singleton before the program ends, you 
can just add an extra class method to set sharedInstance to nil and release the 
object, then -dealloc could do this:

- (void) dealloc
  if (self != sharedInstance)
      [super dealloc];

If you want multiple instances of the class, but never more than one at a time, 
then you wouldn't create them in +initialize (and this wouldn't really be what 
is meant by 'singleton').  In that case you would use a lock to protect 
critical bits of code, have +allocWithZone: return the existing instance (if 
there is one), and have -dealloc reset the sharedInstance variable to nil.

reply via email to

[Prev in Thread] Current Thread [Next in Thread]