美文网首页
单例测试

单例测试

作者: 中隐_隐于市 | 来源:发表于2016-03-03 23:25 被阅读101次

    单例测试

    官方文档:

    dispatch_once
    Executes a block object once and only once for the lifetime of an application.
    void dispatch_once(
    dispatch_once_t *predicate,
    dispatch_block_t block);
    Parameters
    predicate
    A pointer to a dispatch_once_t structure that is used to test whether the block has completed or not.
    block
    The block object to execute once.
    Discussion
    This function is useful for initialization of global data (singletons) in an application. Always call this function before using or testing any variables that are initialized by the block.
    If called simultaneously from multiple threads, this function waits synchronously until the block has completed.
    The predicate must point to a variable stored in global or static scope. The result of using a predicate with automatic or dynamic storage is undefined.
    Availability
    Available in iOS 4.0 and later.

    Declared In
    dispatch/once.h

    //
    //  Onces.m
    //  Once
    //
    //  Created by liulin on 16/3/3.
    //  Copyright (c) 2016年 liulin. All rights reserved.
    //
    
    #import "Onces.h"
    
    @implementation Onces
    
     static Onces *once = nil;
    
    /*
     *  1. 线程安全。
     *  2. 满足静态分析器的要求。
     *  3. 兼容了ARC
     */
    
    + (instancetype)once
    {
        static dispatch_once_t oneToken;
        dispatch_once (&oneToken, ^{
           
            once = [[Onces alloc]init];
        });
        
        return once;
    }
    
    /*
      *  地址唯一性
     */
    
    + (instancetype)allocWithZone:(NSZone *)zone
    {
        
        if (once == nil) {
            once = [super allocWithZone:zone];
        }
        
        return once;
    }
    
    @end
    
    Onces *one = [Onces once];
    
    Onces *one1 = [[Onces alloc]init];
    
    Onces *one2 = [[Onces alloc]init];
    
    NSLog(@"one  == %p,",one);
    
    NSLog(@"one1 == %p,",one1);
    
    NSLog(@"one2 == %p,",one2);
    

    2016-03-04 08:24:11.004 Once[3477:400840] one == 0x7fe9bb7310f0,
    2016-03-04 08:24:11.006 Once[3477:400840] one1 == 0x7fe9bb7310f0,
    2016-03-04 08:24:11.006 Once[3477:400840] one2 == 0x7fe9bb7310f0,

    参考了 多位 大神 博客

    相关文章

      网友评论

          本文标题:单例测试

          本文链接:https://www.haomeiwen.com/subject/illokttx.html