iOS中单例的通用写法

iOS中单例的通用写法(在ARC, MRC下可用),增加了单线程访问限制。

LASingletonPattern.h

#import

@interface LASingletonPattern : NSObject

+ (instancetype)shareInstance;

@end

LASingletonPattern.m

#import "LASingletonPattern.h"

@implementation LASingletonPattern

static id _instance;

+ (instancetype)allocWithZone:(struct _NSZone *)zone {

    if (_instance == nil) {

        @synchronized (self) {

            if (_instance == nil) {

                _instance = [super allocWithZone:zone];

            }

        }

    }

    return _instance;

}

+ (instancetype)shareInstance {

    if (_instance == nil) {

        @synchronized (self) {

            if (_instance == nil) {

                _instance = [[self alloc] init];

            }

        }

    }

    return _instance;

}

#pragma mark - 重写MRC相关方法

- (oneway void)release {

}

- (instancetype)retain {

    return _instance;

}

- (NSUIntegers)retainCount {

    return 1;

}

- (instancetype)autorelease {

    return _instance;

}

- (id)copyWithZone:(NSZone *)zone {

    return _instance;

}

@end

你可能感兴趣的:(iOS中单例的通用写法)