zoukankan      html  css  js  c++  java
  • 单例模式

    iOS中常用的一种模式----单例模式:确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例

    objective-c中要实现一个单例类,至少需要做以下四个步骤:
      1、为单例对象实现一个静态实例,并初始化,然后设置成 nil
      2、实现一个实例构造方法检查上面声明的静态实例是否为 nil,如果是则新建并返回一个本类的实例,
      3、重写 allocWithZone方法,用来保证其他人直接使用 allocinit 试图获得一个新实力的时候不产生一个新实例,
      4 、适当实现allocWitheZone copyWithZonerelease autorelease
     
    整个应用程序中共享一份资源
    +(ShopManager *)shareManager
    {
     static dispatch_once_t once;
     static id instance = nil;
     dispatch_once(&once, ^{
         instance = [[self alloc]init];
     });
      return instance;
    
    }

     用来保存唯一的单例对象, GCD的写法
    static id _instace;
    
    + (id)allocWithZone:(struct _NSZone *)zone
    {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _instace = [super allocWithZone:zone];
        });
        return _instace;
    }
    
    + (instancetype)sharedDataTool
    {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _instace = [[self alloc] init];
        });
        return _instace;
    }
    - (id)copyWithZone:(NSZone *)zone
    {
        return _instace;
    }
  • 相关阅读:
    Linux: 安装和启用firefox浏览器的java
    Latex: beamer
    时频分析:窗口傅立叶变换
    Python: 面向对象
    Linux: 安装NVIDIA显卡驱动
    Matlab: 路径的操作
    python--文件读写
    python--函数
    python--数据类型
    网络基础——网络协议
  • 原文地址:https://www.cnblogs.com/ljmaque/p/iOS.html
Copyright © 2011-2022 走看看