Objective C version

// .h
#import <Foundation/Foundation.h>
@interface TESTSingleton: NSObject
+ (instancetype) shared;

/// blocking alloc/init/new/copy
/// http://stackoverflow.com/questions/5720029/create-singleton-using-gcds-dispatch-once-in-objective-c/22481129#22481129
//+(instancetype) alloc __attribute__((unavailable("alloc not available")));
//-(instancetype) init __attribute__((unavailable("init not available")));
//+(instancetype) new __attribute__((unavailable("new not available")));
//-(instancetype) copy __attribute__((unavailable("copy not available")));
@end


// .m
#import "TESTSingleton.h"
@interface TESTSingleton ()<NSCopying>
@end

@implementation TESTSingleton
static TESTSingleton* instance = nil;
static bool useInside = NO;

/// init call this method returning instance
+ (instancetype) allocWIthZone:(struct _NSZone*)zone {
    static dispatch_once_t onceToken;

    // thread safe
    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;
}

/// 运行时 通过override方法实现成抛异常,可以保证运行时禁止方法调用
+ (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];
    }
}

/// allocWIthZone call this
- (id) copyWithZone:(NSZone*) zone {
    return instance;
}

@end

Swift version

class SingletionClass {
    private init() { }
    static let shared = SingletonClass()
}

results matching ""

    No results matching ""