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、注意:

    • 单例不能被继承
  • 相关阅读:
    改造vue-quill-editor: 结合element-ui上传图片到服务器
    webpack2.X、Vue学习以及将两者相结合
    Vuex-一个专为 Vue.js 应用程序开发的状态管理模式
    vue深究第一弹:computed与watch的异同
    管理系统列表和详情配置
    Vue和vue-template-compiler版本之间的问题
    vuex 闲置状态重置方案
    mac install brew
    Android——推断Service是否已经启动
    【android】uses-permission和permission具体解释
  • 原文地址:https://www.cnblogs.com/66it/p/4719716.html
Copyright © 2011-2022 走看看