iOS中單例的通用寫法

weixin_34337265發表於2017-05-03

iOS中單例的通用寫法(在ARC, MRC下可用),增加了單執行緒訪問限制。

LASingletonPattern.h

#import <Foundation/Foundation.h>

@interface LASingletonPattern : NSObject <NSCopying>

+ (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

相關文章