Skip to content

Instantly share code, notes, and snippets.

@takuma104
Created November 28, 2008 18:31
Show Gist options
  • Save takuma104/30041 to your computer and use it in GitHub Desktop.
Save takuma104/30041 to your computer and use it in GitHub Desktop.
/*
* Obj-C shardInstance(Singlton) Macro
*/
/* example
// header(.h) file
#include "this macro file.h"
@interface SampleClass : NSObject
+ (id)shardInstance;
- (void)hoge;
- (void)fuga;
@end
// objc(.m) file
static SampleClass *shardInstance;
@implementation SampleClass
SHARD_INSTANCE_IMPL
- (void)hoge {
}
- (void)fuga {
}
@end
*/
#define SHARD_INSTANCE_IMPL \
+ (id)shardInstance { \
@synchronized(self) { \
if (shardInstance == nil) { \
[[self alloc] init]; \
} \
} \
return shardInstance; \
} \
\
+ (id)allocWithZone:(NSZone *)zone { \
@synchronized(self) { \
if (shardInstance == nil) { \
shardInstance = [super allocWithZone:zone]; \
return shardInstance; \
} \
} \
return nil; \
} \
\
- (id)copyWithZone:(NSZone *)zone { \
return self; \
} \
\
- (id)retain { \
return self; \
} \
\
- (unsigned)retainCount { \
return UINT_MAX; \
} \
\
- (void)release { \
} \
\
- (id)autorelease { \
return self; \
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment