• iOS-单例模式-使用技巧


    SingleModel-单例模式

    单例可以保证在程序运行过程,一个类只有一个实例(一个对象)

    一般将单例设置成宏,这样在使用的时候可以很方便。

    我们可以按照下面的步骤实现单例

    1、自定义一个.h文件,添加以下代码,这个文件就成了设置单例类的宏文件了。

    
    #define HMSingletonH(name) + (instancetype)shared##name;
    
    
    #if __has_feature(objc_arc)
    
        #define HMSingletonM(name) 
        static id _instace; 
     
        + (id)allocWithZone:(struct _NSZone *)zone 
        { 
            static dispatch_once_t onceToken; 
            dispatch_once(&onceToken, ^{ 
                _instace = [super allocWithZone:zone]; 
            }); 
            return _instace; 
        } 
     
        + (instancetype)shared##name 
        { 
            static dispatch_once_t onceToken; 
            dispatch_once(&onceToken, ^{ 
                _instace = [[self alloc] init]; 
            }); 
            return _instace; 
        } 
     
        - (id)copyWithZone:(NSZone *)zone 
        { 
            return _instace; 
        } 
        - (id)mutableCopyWithZone:(NSZone *)zone 
        { 
            return _instace; 
        }
    
    #else
    
        #define HMSingletonM(name) 
        static id _instace; 
     
        + (id)allocWithZone:(struct _NSZone *)zone 
        { 
            static dispatch_once_t onceToken; 
            dispatch_once(&onceToken, ^{ 
                _instace = [super allocWithZone:zone]; 
            }); 
            return _instace; 
        } 
     
        + (instancetype)shared##name 
        { 
            static dispatch_once_t onceToken; 
            dispatch_once(&onceToken, ^{ 
                _instace = [[self alloc] init]; 
            }); 
            return _instace; 
        } 
     
        - (id)copyWithZone:(NSZone *)zone 
        { 
            return _instace; 
        } 
        - (id)mutableCopyWithZone:(NSZone *)zone 
        { 
            return _instace; 
        } 
     
        - (oneway void)release { } 
        - (id)retain { return self; } 
        - (NSUInteger)retainCount { return 1;} 
        - (id)autorelease { return self;}
    
    #endif
    

    2、要想使某一个类成为一个单例,只需要在这个的类的.h和.m
    文件里面添加下面两句即可成为单例。

    .h文件

    HMSingletonH(类名)
    

    .m文件

    HMSingletonM(类名)
    

    3、注意:

    • 单例不能被继承
  • 相关阅读:
    NSUserDefaults写作和阅读对象定义自己
    JavaScript三在弹出的对话框中
    mybatis02 架构
    mybatis01
    oracle17 视图
    oracle16 例外
    oracle15 pl/sql 分页
    oracle14 复杂数据类型
    oracle13 触发器 变量
    oracle12 pl/sql
  • 原文地址:https://www.cnblogs.com/66it/p/4719716.html
Copyright © 2020-2023  润新知