zoukankan      html  css  js  c++  java
  • OC单例模式的实现

    SingleClass.m

    #import <Foundation/Foundation.h>
    @class SingleClass;
    
    static SingleClass *instance = nil;
    
    @interface SingleClass : NSObject <NSCopying>
    + (instancetype)shareInstance;
    @end
    
    @implementation SingleClass
    //类方法,获取单例对象
    + (instancetype)shareInstance{
        if (!instance) {
            instance = [[self alloc] init];
        }
        return instance;
    }
    //类方法,调用对象的alloc方法时返回已存在的单例
    + (instancetype)allocWithZone:(struct _NSZone *)zone{
        if (!instance) {
            instance = [super allocWithZone:zone];
        }
        return instance;
    }
    //copy时,返回已存在的单例
    - (id)copyWithZone:(NSZone *)zone{
        return instance;
    }
    //copy时,返回已存在的单例
    - (id)copy{
        return instance;
    }
    @end

    main.m

    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            SingleClass *s1 = [SingleClass shareInstance];
            SingleClass *s2 = [SingleClass shareInstance];
            SingleClass *s3 = [[SingleClass alloc] init];
            SingleClass *s4 = [s1 copy];
            
            NSLog(@"%p",s1);
            NSLog(@"%p",s2);
            NSLog(@"%p",s3);
            NSLog(@"%p",s4);
        }
        return 0;
    }

    结果:

    2015-03-22 22:24:21.201 SingleDemo[1349:61326] 0x1001066e0
    2015-03-22 22:24:21.202 SingleDemo[1349:61326] 0x1001066e0
    2015-03-22 22:24:21.202 SingleDemo[1349:61326] 0x1001066e0
    2015-03-22 22:24:21.202 SingleDemo[1349:61326] 0x1001066e0
  • 相关阅读:
    Django部署在CENTOS7上
    慕课DJANGO配置
    响应式布局组件介绍
    SYN泛洪攻击原理及防御
    Token,session,cookie
    -webkit-
    JS中dataTransfer对象在拖曳操作中的妙用。
    深入理解DOM节点类型第一篇——12种DOM节点类型概述
    js如何打印object对象
    cookie(2)
  • 原文地址:https://www.cnblogs.com/yoran-yang/p/4358252.html
Copyright © 2011-2022 走看看