原创帖子,转载请注明出处:http://blog.csdn.net/sbvfhp/article/details/47861453
单例的一种优秀方案,整个项目只需要这一段代码,其它需要单例的地方import一下就可以了。
// Created by 李建 on 15/8/22.
// Copyright (c) 2015年 李建. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSObject (SingletonCategory)
+ (id)sharedInstance:(NSString *)className;
@end
// Created by 李建 on 15/8/22.
// Copyright (c) 2015年 李建. All rights reserved.
//
#import "NSObject+SingletonCategory.h"
static NSMutableDictionary *instanceDic;
@implementation NSObject (SingletonCategory)
+ (id)sharedInstance:(NSString *)className
{
if (!instanceDic) {
instanceDic = [NSMutableDictionary dictionary];
}
@synchronized(self){
id _instance = [instanceDic objectForKey:className];
if (_instance) {
return _instance;
}else{
id newInstance = [[self alloc] init];
[instanceDic setValue:newInstance forKey:className];
return newInstance;
}
}
}