-
声明两个全局的静态实例
static dispatch_once_t _oneToken;
static ExampleManager _instance;
-
重写allocWithZone方法.此方法为对象分配空间必须调用方法.
+(ExampleManager *)shareInstance{
dispatch_once(&_oneToken, ^{
_instance = [[ExampleManager alloc] init];
});
return _instance;
}
- 保证copy时相同
-(id)copyWithZone:(NSZone *)zone{
return _instance;
}
- 释放资源
-(void)destroyInstance{
/*
只有置成0,GCD才会认为它从未执行过.它默认为0.这样才能保证下次再次调用shareInstance的时候,再次创建对象.
*/
_oneToken = 0;
_instance = nil;
}
用法实例
ExampleManager *example = [ExampleManager shareInstance];
[[ExampleManager shareInstance] destroyInstance];
网友评论