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: - Yes, this implementation uses synchronize (grab a lock) and not any broken double check, etc. scheme as outline in the PDF you referenced.


#import <Foundation/Foundation.h>

@interface FTSWAbstractSingleton : NSObject { }

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


#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.


The following is an example sub-class…

#import “FTSWAbstractSingleton.h”

@interface MySingleton : FTSWAbstractSingleton { …blah… }

@implementation MySingleton

…blah… @end