CocoaDev

Edit AllPages

Hope folks find this code useful. Please point out any defects or improvements. -ShawnErickson

The following code is an implementation of a base class that allows sub-classes to inherit singleton behavior including preventing deallocation of the singleton instance and related enforcement of the contract. This implementation is also thread safe.

(Are you sure? See: http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf) - Yes, this implementation uses synchronize (grab a lock) and not any broken double check, etc. scheme as outline in the PDF you referenced.

FTSWAbstractSingleton.h

#import <Foundation/Foundation.h>

@interface FTSWAbstractSingleton : NSObject { }

//designated initializer, subclasses must implement and call supers implementation

FTSWAbstractSingleton.m

#import “FTSWAbstractSingleton.h”

@implementation FTSWAbstractSingleton

static NSMutableDictionary *s_FTSWAbstractSingleton_singletons = nil;

// Should be considered private to the abstract singleton class, // wrap with a “sharedXxx” class method

// Should be considered private to the abstract singleton class

// Designated initializer for instances. If subclasses override they // must call this implementation.

// Disallow the normal default initializer for instances.

// —————————————————————————— // The following overrides attempt to enforce singleton behavior.

@end


The following is an example sub-class…

#import “FTSWAbstractSingleton.h”

@interface MySingleton : FTSWAbstractSingleton { …blah… }

@implementation MySingleton

…blah… @end