シングルケーステスト
1974 ワード
シングルケーステスト
公式ドキュメント:
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
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,
公式ドキュメント:
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,