Objective C version
#import <Foundation/Foundation.h>
@interface TESTSingleton: NSObject
+ (instancetype) shared;
@end
#import "TESTSingleton.h"
@interface TESTSingleton ()<NSCopying>
@end
@implementation TESTSingleton
static TESTSingleton* instance = nil;
static bool useInside = NO;
+ (instancetype) allocWIthZone:(struct _NSZone*)zone {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [super allocWithZone: zone];
});
return instance;
}
+ (instancetype) shared {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
useInside = YES;
instance = [[TESTSingleton alloc] init];
useInside = NO;
});
return instance;
}
+ (id) alloc {
if (!useInside) {
@throw [NSException exceptionWithName:@"Singleton Vialotaion"
reason:@"You are violating the singleton class usage. Please call +sharedInstance method"
userInfo:nil];
} else {
return [super alloc];
}
}
- (id) copyWithZone:(NSZone*) zone {
return instance;
}
@end
Swift version
class SingletionClass {
private init() { }
static let shared = SingletonClass()
}