单例模式在iOS开发过程中经常用到,苹果提供过objective c单例的比较官方的写法:
- static MyGizmoClass *sharedGizmoManager = nil;
- + (MyGizmoClass*)sharedManager
- {
- @synchronized(self) {
- if (sharedGizmoManager == nil) {
- [[self alloc] init]; // assignment not done here
- }
- }
- return sharedGizmoManager;
- }
- + (id)allocWithZone:(NSZone *)zone
- {
- @synchronized(self) {
- if (sharedGizmoManager == nil) {
- sharedGizmoManager = [super allocWithZone:zone];
- return sharedGizmoManager; // assignment and return on first allocation
- }
- }
- return nil; //on subsequent allocation attempts return nil
- }
- - (id)copyWithZone:(NSZone *)zone
- {
- return self;
- }
- - (id)retain
- {
- return self;
- }
- - (unsigned)retainCount
- {
- return UINT_MAX; //denotes an object that cannot be released
- }
- - (void)release
- {
- //do nothing
- }
- - (id)autorelease
- {
- return self;
- }
现在iOS5之后普遍使用了ARC技术,原来这个写法就显得很累赘了,release已经不使用了。
咱们可以结合GCD来实现单例模式:
- + (id)sharedInstance
- {
- static dispatch_once_t pred = 0;
- __strong static id _sharedObject = nil;
- dispatch_once(&pred, ^{
- _sharedObject = [[self alloc] init]; // or some other init method
- });
- return _sharedObject;
- }
因为我们可能需要多个单例的类,每个都写一次比较麻烦,可以更方便一些,把这些代码写成宏的形式,只需要传入类名就可以创建一个单例的类了。
通过传入类名创建头文件中单例方法的名称:
- #define DEFINE_SINGLETON_FOR_HEADER(className) \
- \
- + (className *)shared##className;
- #define DEFINE_SINGLETON_FOR_CLASS(className) \
- \
- + (className *)shared##className { \
- static className *shared##className = nil; \
- static dispatch_once_t onceToken; \
- dispatch_once(&onceToken, ^{ \
- shared##className = [[self alloc] init]; \
- }); \
- return shared##className; \
- }
使用宏:
在项目中新建了一个类testSingleton,并且有.h 和.m文件。
.h
.m中的代码:
- #import <Foundation/Foundation.h>
- @interface testSingleton : NSObject
- DEFINE_SINGLETON_FOR_HEADER(testSingleton);
- @end
- #import "testSingleton.h"
- @implementation testSingleton
- DEFINE_SINGLETON_FOR_CLASS(testSingleton)
- @end
获取单例:
- - (void)test
- {
- testSingleton *testShare = [testSingleton sharedtestSingleton];
- }
转自:http://blog.csdn.net/totogo2010/article/details/8373642