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;
    }
  • 相关阅读:
    关于获取多个id的用法
    纯css打造凹进与突出效果
    ie8兼容半透明效果css
    常用函数积累
    ie兼容图片缩小后模糊失真(锯齿)问题
    图片放大_css3
    弹出层跳出原框架
    ifame_自适应高度
    POJ #2479
    SPOJ #752. Power it!
  • 原文地址:https://www.cnblogs.com/ljmaque/p/iOS.html
Copyright © 2011-2022 走看看