编辑
iOS单例模式
本文访问次数:0

iOS下如何使用单例模式,请参考以下代码

@interface Singleton : NSObject
+ (Singleton*)sharedInstance;
@end
#import "Singleton.h"

@implementation Singleton

static Singleton* SINGLETON = nil;

static bool isFirstAccess = YES;

#pragma mark - Public Method

+ (id)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once (&onceToken, ^{
        isFirstAccess = NO;
        SINGLETON = [[super allocWithZone:NULL] init];
    });

    return SINGLETON;
}

#pragma mark - Life Cycle

+ (id)allocWithZone:(NSZone*)zone {
    return [self sharedInstance];
}

+ (id)copyWithZone:(struct _NSZone*)zone {
    return [self sharedInstance];
}

+ (id)mutableCopyWithZone:(struct _NSZone*)zone {
    return [self sharedInstance];
}

- (id)copy {
    return [[Singleton alloc] init];
}

- (id)mutableCopy {
    return [[Singleton alloc] init];
}

- (id)init {
    if (SINGLETON) {
        return SINGLETON;
    }
    if (isFirstAccess) {
        [self doesNotRecognizeSelector:_cmd];
    }
    self = [super init];
    return self;
}

@end

注意对默认构造函数做了处理,可以避免产生多个实例。

没有任何评论