单例模板一则

参考我上一篇转载的博文,我对单例模板做出了一些修改,用起来的话会变得更加方便一点:

//

// SynthesizeSingleton.h

// CocoaWithLove

//

// Created by Matt Gallagher on 20/10/08.

// Copyright 2009 Matt Gallagher. All rights reserved.

//

// Permission is given to use this source code file without charge in any

// project, commercial or otherwise, entirely at your risk, with the condition

// that any redistribution (in part or whole) of source code must retain

// this copyright and permission notice. Attribution in compiled projects is

// appreciated but not required.

//


#define SYNTHESIZE_SINGLETON_FOR_CLASS(classname) \

\

static classname *instance = nil; \

\

+ (classname *)getInstance \

{ \

@synchronized(self) \

{ \

if (instance == nil) \

{ \

instance = [[self alloc] init]; \

} \

} \

\

return instance; \

} \

\

+ (id)allocWithZone:(NSZone *)zone \

{ \

@synchronized(self) \

{ \

if (instance == nil) \

{ \

instance = [super allocWithZone:zone]; \

return instance; \

} \

} \

\

return nil; \

} \

\

- (id)copyWithZone:(NSZone *)zone \

{ \

return self; \

} \

\

- (id)retain \

{ \

return self; \

} \

\

- (NSUInteger)retainCount \

{ \

return NSUIntegerMax; \

} \

\

- (void)release \

{ \

} \

\

- (id)autorelease \

{ \

return self; \

}

有了上面的宏模板,就再也不用机械化的多次复制粘贴以下代码了:

/**

*单例~

*/

+(AudioManager*) getInstance {

staticAudioManager*instance;

@synchronized(self) {

if(!instance) {

instance = [[selfalloc]init];

}

}

returninstance;

}

其实本质来说,还是粘贴复制,不过现在只要复制粘贴一句了

SYNTHESIZE_SINGLETON_FOR_CLASS(AudioManager)

你可能感兴趣的:(单例)