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

    • 单例不能被继承
  • 相关阅读:
    MinGW-编译器
    Enum , Enum Class ?
    C++编译器之间的不同性能
    交叉验证
    经验风险最小化-结构风险最小化
    图像卷积
    pytorch官网上两个例程
    ORB feature(O for orientation)
    Catalan数
    无责任共享 Coursera、Udacity 等课程视频(转载)
  • 原文地址:https://www.cnblogs.com/66it/p/4719716.html
Copyright © 2011-2022 走看看