欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

iOS单例写法

程序员文章站 2022-07-13 23:45:40
...
#import <Foundation/Foundation.h>

@interface Singleton : NSObject<NSCopying,NSMutableCopying>
+ (instancetype)shareInstance;
@end
#import "Singleton.h"

@implementation Singleton

static Singleton *instance = nil;

/*
//不使用GCD的写法
+ (instancetype)shareInstance {
    
    if (instance == nil) {
        instance = [[super allocWithZone:NULL] init];
        NSLog(@"执行一次");
    }
    
    return instance;
}
*/


//使用GCD
+ (instancetype)shareInstance {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[super allocWithZone:NULL] init];
    });
    
    return instance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    return [Singleton shareInstance];
}

- (instancetype)copyWithZone:(nullable NSZone *)zone {
    return [Singleton shareInstance];
}

- (instancetype)mutableCopyWithZone:(nullable NSZone *)zone {
    return [Singleton shareInstance];
}
@end

参考链接:IOS单例的写法