重写美味不用等(1) 单例 --initialize方法调用

initialize实在一个类第一次发消息前调用,就是说,第一次调用init, 私用方法, 类方法调用之前会调用它,也只调用一次。

.h文件

+ (instancetype)sharedInstance;

.m文件

static DataManager *dataManager;

+ (instancetype)sharedInstance{

    return dataManager;

}


+ (void)initialize{

    if (!dataManager) {

        dataManager = [[DataManager alloc]init];

    }

}

还有一种宏定义写法 

//

//  Singelton.h

//  NoWait

//

//  Created by liu nian on 15/3/30.

//  Copyright (c) 2015 Shanghai Puscene Information Technology Co.,Ltd. All rights reserved.

//


#ifndef NoWait_Singelton_h

#define NoWait_Singelton_h


//http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/nsobject_Class/Reference/Reference.html#//apple_ref/occ/clm/NSObject/initialize


#define SingletonInterface(Class) \

+ (Class *)sharedInstance;



#define SingletonImplementation(Class) \

static Class *__ ## sharedSingleton; \

\

\

+ (void)initialize \

{ \

static BOOL initialized = NO; \

if(!initialized) \

{ \

initialized = YES; \

__ ## sharedSingleton = [[Class alloc] init]; \

} \

} \

\

\

+ (Class *)sharedInstance \

{ \

return __ ## sharedSingleton; \

} \

\


#endif



你可能感兴趣的:(重写美味不用等(1) 单例 --initialize方法调用)