SynthesizeSingleton Macro

| Comments

Reading Learning iOS Game Programming book by Michael Daley, i found this handy class created by Matt Gallagher. SynthesizeSingleton macro enables you to turn a class into a singleton class simply by adding a line of code to your header and another to your implementation. The intent of the Singleton pattern as defined in Design Patterns is to “ensure a class has only one instance, and provide a global point of access to it”.

Implementation

//
//  SoundManager.h
//  SoundManager
//
//  Created by Raúl Uranga on 11/15/10.
//  Copyright 2010 GrupoW. All rights reserved.
//

#import "SynthesizeSingleton.h"

@interface SoundManager : NSObject {
}

// Class method to return an instance of SoundManager.
+ (SoundManager *)sharedSoundManager;

//Instance methods.
- (id)init;
- (NSUInteger)playSoundWithKey:(NSString*)aSoundKey;
- (void)loadSoundWithKey:(NSString*)aSoundKey fileName:(NSString*)aFileName fileExt:(NSString*)aFileExt;

@end




//
//  SoundManager.m
//  SoundManager
//
//  Created by Raúl Uranga on 11/15/10.
//  Copyright 2010 GrupoW. All rights reserved.
//

#import "SoundManager.h"

@implementation SoundManager

//here is when the magic happens
SYNTHESIZE_SINGLETON_FOR_CLASS(SoundManager);

- (id)init {
       //
}

- (NSUInteger)playSoundWithKey:(NSString*)aSoundKey
{
      //
}

- (void)loadSoundWithKey:(NSString*)aSoundKey fileName:(NSString*)aFileName fileExt:(NSString*)aFileExt
{
     //
}

- (void)dealloc {
    [super dealloc];
}

@end

The name of the class method defined in the header is important; it should be shared, followed by the name of the class (for example, sharedClassName). The class name is passed to the macro in the implementation, and it is used to create the sharedClassName method.

SynthesizeSingleton.h file

for more information on creating a singleton from Apple can be found here.

Comments