zoukankan      html  css  js  c++  java
  • 创建线程安全的单例(ARC或 非ARC)

    一:创建 宏 文件 SynthesizeSingleton.h

    SynthesizeSingleton.h
    
    #if __has_feature(objc_arc) // ARC Version
    
    #define SYNTHESIZE_SINGLETON_FOR_CLASS(classname)   
    
    + (classname *)shared##classname
    {
        static classname *shared##classname = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            shared##classname = [[classname alloc] init];
        });
        return shared##classname;
    }
    
    #else // Non-ARC Version
    
    #define SYNTHESIZE_SINGLETON_FOR_CLASS(classname) 
    static classname *shared##classname = nil; 
    + (classname *)shared##classname 
    { 
        @synchronized(self) 
        { 
            if (shared##classname == nil) 
            { 
                shared##classname = [[self alloc] init]; 
            } 
        } 
        return shared##classname; 
    } 
    
    + (id)allocWithZone:(NSZone *)zone 
    { 
    @synchronized(self) 
    { 
    if (shared##classname == nil) 
    { 
    shared##classname = [super allocWithZone:zone]; 
    return shared##classname; 
    } 
    } 
    return nil; 
    } 
    - (id)copyWithZone:(NSZone *)zone 
    { 
    return self; 
    } 
    - (id)retain 
    { 
    return self; 
    } 
    - (NSUInteger)retainCount 
    { 
    return NSUIntegerMax; 
    } 
    - (oneway void)release 
    { 
    } 
    - (id)autorelease 
    { 
    return self; 
    }
    
    #endif
    

      二:使用

    MyClass.h
    
    @interface MyClass : NSObject
    
    +(DataStorage *)sharedMyClass;
    
    @end
    MyClass.m
    
    #import "SynthesizeSingleton.h"
    @implementation MyClass
    SYNTHESIZE_SINGLETON_FOR_CLASS(MyClass)
    @end
    

     参考资料

  • 相关阅读:
    Python之数学(math)和随机数(random)
    《图解HTTP》读书笔记
    leetcode1008
    leetcode1007
    leetcode1006
    leetcode1005
    leetcode218
    leetcode212
    leetcode149
    leetcode140
  • 原文地址:https://www.cnblogs.com/cocoajin/p/3176265.html
Copyright © 2011-2022 走看看