iOS开发学习笔记(OC语言)——线程安全的单例

SingleClass.h

//
//  SingleClass.h
//  First
//
//  Created by xxx on 2022/2/9.
//

#import <Foundation/Foundation.h>

@interface SingleClass : NSObject

+(instancetype) sharedInstance;

@end

SingleClass.m

//
//  SingleClass.m
//  First
//
//  Created by xxx on 2022/2/9.
//

#import "SingleClass.h"

@implementation SingleClass

+ (instancetype)sharedInstance {
    static SingleClass * ins = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        ins = [[super allocWithZone:nil] init];
    });
    
    return ins;
}

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

-(id)copyWithZone:(NSZone *) zone {
    return [[self class] sharedInstance];
}

-(id)mutableCopyWithZone:(NSZone *) zone {
    return [[self class] sharedInstance];
}

@end

测试

#import "SingleClass.h"



SingleClass *ins1 = [SingleClass sharedInstance];
NSLog(@"SingleClass obj1 = %@.", ins1);
    
SingleClass *ins2 = [[SingleClass alloc] init];
NSLog(@"SingleClass obj2 = %@.", ins2);
    
SingleClass *ins3 = [SingleClass new];
NSLog(@"SingleClass obj3 = %@.", ins3);
    
if (ins1 == ins2 && ins1 == ins3) {
    NSLog(@"SingleClass test success");
} else {
    NSLog(@"SingleClass test failed");
}
posted @ 2022-02-14 13:49  观海云不远  阅读(158)  评论(0编辑  收藏  举报