#import <Foundation/Foundation.h>
@interface DLGSingleton : NSObject
// "+" 表示类的方法,由类调用
+(DLGSingleton *)sharedInstance;
@end
#import "DLGSingleton.h"
// 用static申明一个类的静态实例,
static DLGSingleton *_sharedInstance =nil;
@implementation DLGSingleton
+(DLGSingleton *)sharedInstance{
@synchronized(self) {
if (_sharedInstance==nil) {
[[self alloc]init];
}
}
return _sharedInstance;
}
+(instancetype)allocWithZone:(struct _NSZone *)zone{
@synchronized(self) {
if (_sharedInstance==nil) {
_sharedInstance = [super allocWithZone:zone];
}
return _sharedInstance;
}
}
-(id)copyWithZone:(struct_NSZone *)zone{
return self;
}
@end
方法二:
+(SingletonManager *)sharedInstance
{
static SingletonManager *sharedManager;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedManager = [[SingletonManager alloc] init];
});
return sharedManager;
}
SingletonManager *Manager = [SingletonManager sharedInstance];