zoukankan      html  css  js  c++  java
  • 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、注意:

    • 单例不能被继承
  • 相关阅读:
    C# EPPlus 导出Excel
    NetCore +EF+Mysql 从数据库生成实体类到项目
    VBA链接SQL server数据库
    sqlserver中的 binary varbinary image
    sql server DateTime与DateTime2的区别
    Sql Server增删改查字段的语法
    c#中queue的用法
    Sql Server中不相关的两个数据表的全部显示
    IActionResult的返回值类型
    linux内存映射
  • 原文地址:https://www.cnblogs.com/66it/p/4719716.html
Copyright © 2011-2022 走看看