单例为存储在全局静态区的对象,只初始化一次,且内存唯一,不管创建多少次,永远得到的都是第一次创建的对象,永不释放,直到程序退出时才内存回收;
单例的创建方法:新建一个类继承于nsobject
在.h文件里:
写一个类方法:
+ (ShareInstance *)shareInstance;
在.m文件中:
#import "ShareInstance.h"
static ShareInstance *share = nil;
@implementation ShareInstance
// 通过类方法来创建对象,在方法内避免多次调用alloc
+ (ShareInstance *)shareInstance
{
// 单例线程安全
// 第一种
// @synchronized(self){
// if (!share) {
// share = [[ShareInstance alloc] init];
// share.arr = [NSMutableArray array];
// share.dic = [NSMutableDictionary dictionary];
// }
// return share;
// }
// 第二种
static dispatch_once_t once;
dispatch_once(&once, ^{
share = [[ShareInstance alloc] init];
share.arr = [NSMutableArray array];
share.dic = [NSMutableDictionary dictionary];
});
return share;
}
@end