zoukankan      html  css  js  c++  java
  • iOS边练边学--iOS中的(ARC下)单粒模式(GCD实现)

    一、ARC中实现单粒模式

    • 在.m 保留一个全局的static的实例  static id _名称;
    • 重写allocWithZone:方法,在这里创建唯一的实例

    • 提供一个类方法让外界访问唯一的实例

    • 实现copyWithZone:方法 -- 方法中直接返回static修饰的全局变量,copy是对象方法,所以调用copy就说明已经有了单例对象

    二、单粒模式 宏 的定义

    • 定义一个.h文件就搞定

    • 单粒模式使用

        

     1 // .h文件  宏中的## 用来转译
     2 #define XMGSingletonH(name) + (instancetype)shared##name;
     3 
     4 // .m文件  宏的定义默认是一行,多行用,然后宏就能识别了
     5 #define XMGSingletonM(name) 
     6 static id _instance; 
     7  
     8 + (instancetype)allocWithZone:(struct _NSZone *)zone 
     9 { 
    10     static dispatch_once_t onceToken; 
    11     dispatch_once(&onceToken, ^{ 
    12         _instance = [super allocWithZone:zone]; 
    13     }); 
    14     return _instance; 
    15 } 
    16  
    17 + (instancetype)shared##name 
    18 { 
    19     static dispatch_once_t onceToken; 
    20     dispatch_once(&onceToken, ^{ 
    21         _instance = [[self alloc] init]; 
    22     }); 
    23     return _instance; 
    24 } 
    25  
    26 - (id)copyWithZone:(NSZone *)zone 
    27 { 
    28     return _instance; 
    29 }
  • 相关阅读:
    二叉树后序遍历
    [编程题] 赛马
    [编程题] 糖果谜题 C++实现输入未知个整数
    [编程题] 时钟
    [编程题] 会话列表
    A Fast Lock-Free Queue for C++
    Design Hangman
    Design a URL shortener [转]
    ostream 和 ostringsteam 的区别
    Hash Table Collision Handling
  • 原文地址:https://www.cnblogs.com/gchlcc/p/5432548.html
Copyright © 2011-2022 走看看