美文网首页
使用宏封装单例

使用宏封装单例

作者: 希达like | 来源:发表于2019-05-28 14:33 被阅读0次
    一、单例使用
    1. 使用方法 .h
     #import <Foundation/Foundation.h>
    
    @interface MineAuthentication :NSObject
    
    SHSingleInstance_H_(AuthenticationManager )
    
    @end
    

    2.使用方法.m

    #import "SHMineAuthentication.h"
    
    @interface MineAuthentication ()
    
    @end
    
    
    @implementation MineAuthentication
    
    SHSingleInstance_M_(AuthenticationManager )
    
    
    @end
    
    二、单例实现和定义
     //1.单例实现和定义宏--方便.h文件使用
    
    #define SHSingleInstance_H_(name) \
    
    + (instancetype)shared##name;
    
    //2.单例实现和定义宏--方便.m文件使用
    
    #define SHSingleInstance_M_(name) \
    
    static id _instance = nil; \
    
    + (instancetype)shared##name \
    
    { \
    
    static dispatch_once_t onceToken; \
    
    dispatch_once(&onceToken, ^{ \
    
    if (_instance == nil) \
    
    { \
    
    _instance = [[self alloc] init]; \
    
    } \
    
    }); \
    
    return _instance; \
    
    } \
    
    \
    
    + (instancetype)allocWithZone:(struct _NSZone *)zone \
    
    { \
    
    static dispatch_once_t onceToken; \
    
    dispatch_once(&onceToken, ^{ \
    
    if (_instance == nil) \
    
    { \
    
    _instance = [super allocWithZone:zone]; \
    
    } \
    
    }); \
    
    return _instance; \
    
    } \
    
    \
    
    + (id)copyWithZone:(struct _NSZone *)zone \
    
    { \
    
    return _instance; \
    
    } \
    
    + (id)mutableCopyWithZone:(struct _NSZone *)zone \
    
    { \
    
    return _instance; \
    
    }
    
    三、单例调用
     [MineAuthenticationsharedAuthenticationManager];
    

    摘录自原文:https://blog.csdn.net/shihuboke/article/details/78235099

    相关文章

      网友评论

          本文标题:使用宏封装单例

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