Skip to content

Instantly share code, notes, and snippets.

@andrewgarn
Created May 4, 2012 08:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewgarn/2593411 to your computer and use it in GitHub Desktop.
Save andrewgarn/2593411 to your computer and use it in GitHub Desktop.
Macro for creating objective-c singleton with custom accessor that supports both arc (GCD) and non arc environments
//
// AGSynthesizeSingleton.h
// Agnomical SDK
//
// Created by Andrew Garn on 22/03/2012.
// Copyright (c) 2012 Andrew Garn. All rights reserved.
//
/**
Singleton interface method macro
*/
#define SYNTHESIZE_SINGLETON_FOR_INTERFACE(CLASSNAME, ACCESSOR) \
+ (CLASSNAME *)ACCESSOR;
/**
Singleton implementation method macro
*/
#if __has_feature(objc_arc)
#define SYNTHESIZE_SINGLETON_FOR_IMPLEMENTATION(CLASSNAME, ACCESSOR) \
\
__strong static CLASSNAME *__##ACCESSOR = nil; \
\
+ (CLASSNAME *)ACCESSOR \
{ \
static dispatch_once_t pred; \
dispatch_once(&pred, ^{ \
__##ACCESSOR = [[self alloc] init]; \
}); \
return __##ACCESSOR; \
} \
#else
#define SYNTHESIZE_SINGLETON_FOR_IMPLEMENTATION(CLASSNAME, ACCESSOR) \
\
static CLASSNAME *__##ACCESSOR = nil; \
\
+ (CLASSNAME *)ACCESSOR \
{ \
@synchronized(self) \
{ \
if (__##ACCESSOR == nil) \
{ \
__##ACCESSOR = [[self alloc] init]; \
} \
} \
\
return __##ACCESSOR; \
} \
\
+ (id)allocWithZone:(NSZone *)zone \
{ \
@synchronized(self) \
{ \
if (__##ACCESSOR == nil) \
{ \
__##ACCESSOR = [super allocWithZone:zone]; \
return __##ACCESSOR; \
} \
} \
\
return nil; \
} \
\
- (id)copyWithZone:(NSZone *)zone \
{ \
return self; \
} \
\
- (id)retain \
{ \
return self; \
} \
\
- (NSUInteger)retainCount \
{ \
return NSUIntegerMax; \
} \
\
-(oneway void)release \
{ \
} \
\
- (id)autorelease \
{ \
return self; \
}
#endif
//
// FileManager.h
// Agnomical SDK
//
// Created by Andrew Garn on 04/05/2012.
// Copyright (c) 2012 Andrew Garn. All rights reserved.
//
@interface FileManager : NSObject
{
}
SYNTHESIZE_SINGLETON_FOR_INTERFACE(FileManager, sharedManager);
@end
//
// FileManager.m
// Agnomical SDK
//
// Created by Andrew Garn on 04/05/2012.
// Copyright (c) 2012 Andrew Garn. All rights reserved.
//
@implementation FileManager
SYNTHESIZE_SINGLETON_FOR_IMPLEMENTATION(FileManager, sharedManager);
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment