IOS单例创建写法

.h文件

#import 

NS_ASSUME_NONNULL_BEGIN

@interface CustomManger : NSObject
@property (nonatomic, assign)int count;
+ (CustomManger *)shareCustomerManger;

@end

NS_ASSUME_NONNULL_END

.m文件

@implementation CustomManger

static CustomManger *_manger = nil;
+ (CustomManger *)shareCustomerManger
{
//用dispatch_once保证内存只分配一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manger = [[super allocWithZone:NULL] init];
    });
    return _manger;
}

-(instancetype)init
{
    if ([super init]) {
        NSLog(@"%s",__func__);
        static dispatch_once_t onceToken;
               dispatch_once(&onceToken, ^{
                   //如果有数据初始化时,需要保证初始化也只进行一次
                   self.count = 10;
               });
        
    }
    
    return self;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    NSLog(@"%s",__func__);
    return [CustomManger shareCustomerManger];
}

//对对象使用copy也是返回唯一实例
-(instancetype)copyWithZone:(NSZone *)zone {
    
    return  [CustomManger shareCustomerManger];
}

 //对对象使用mutablecopy也是返回唯一实例
-(instancetype)mutableCopyWithZone:(NSZone *)zone {
    
    return  [CustomManger shareCustomerManger];
}

@end

你可能感兴趣的:(IOS单例创建写法)