美文网首页
8.1.加锁-单例

8.1.加锁-单例

作者: 草根小强 | 来源:发表于2019-04-22 15:53 被阅读0次

    加锁-单例

    #import "ViewController.h"
    #import "Single.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        Single *single = [Single shareSingle];
        NSLog(@"%@",single);
        
        Single *obj = [[Single alloc]init];
        NSLog(@"%@",obj);
        
        Single *obj1 = [[Single alloc]init];
        NSLog(@"%@",obj1);
        
        Single *obj2 = [[Single alloc]init];
        NSLog(@"%@",obj2);
        
        Single *obj3 = [obj2 copy];
        NSLog(@"%@",obj3);
    }
    
    
    @end
    
    
    #import <Foundation/Foundation.h>
    
    @interface Single : NSObject<NSCopying>
    
    
    //创建单例对象
    +(instancetype)shareSingle;
    
    
    
    @end
    
    
    #import "Single.h"
    #import <UIKit/UIKit.h>
    
    @implementation Single
    
    //全局的静态变量
    static id obj;//默认是nil
    
    +(instancetype)shareSingle{
        
    //    static Single *obj = nil;
    #if 0
        if (!obj) {
            
            obj = [[self alloc]init];
        }
    #elif 0
        //加锁 同一时刻只允许一个线程访问
        @synchronized(self) {
            if (!obj) {
                
                obj = [[self alloc]init];
            }
        }
    #elif 1
        //GCD加锁  dispatch_once_t只会执行一次
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            
            obj = [[self alloc]init];
        });
    
    #endif
    
        return obj;
    }
    
    //重写这个方法 可以让我们用alloc创建的对象也是同一份对象
    +(instancetype)allocWithZone:(struct _NSZone *)zone{
        
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            obj = [super allocWithZone:zone];
        });
        
        return obj;
    }
    
    //重写这个方法 copy的对象也是同一份对象
    -(id)copyWithZone:(NSZone *)zone{
        
        return obj;
    }
    
    
    
    
    @end
    
    
    加锁-单例.png

    相关文章

      网友评论

          本文标题:8.1.加锁-单例

          本文链接:https://www.haomeiwen.com/subject/xjzygqtx.html