iOS 单例模式

ARC,

static Singleton *kEntity = nil;

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    if (kEntity == nil) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{    
            kEntity = [super allocWithZone:zone];
        });
    }
    return kEntity;
}

- (instancetype)init
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        kEntity = [super init];
    });
    return kEntity;
}

+ (instancetype) shareEntity
{
    return [[self alloc] init];
}
要遵守NSCopying协议
- (id) copyWithZone:(NSZone *)zone
{
    return self;
}

MRC 加上

- (onewav void) release
{
}

- (id) retain
{
    return self;
}

- (NSInteger) retainCount
{
    return 1;
}


你可能感兴趣的:(iOS 单例模式)