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
    

     参考资料

  • 相关阅读:
    使用基本的socket函数
    ODBC、ADO
    MFC开发ActiveX控件的简介
    MFC线程
    系统API函数实现多线程及线程同步
    IP地址控件
    加速键
    属性页对话框
    Tab控件
    树控件
  • 原文地址:https://www.cnblogs.com/cocoajin/p/3176265.html
Copyright © 2011-2022 走看看