单例模式只能修改无法释放,直到程序结束
单例模式的创建:
1.单例模式一旦创建,是永远存在于内存中.所以需要创建一个全局变量
Static MySingletonClass *sharedSingletonObj=nil;
2.单例模式,一定有一个构造方法直接忽略跳过实例对象的生成过程.据此看来”类方法”最合适不过了
+(MySingletonClass*)sharedSingleton{
@synchronized(self){
//创建
If(sharedSingletonObj==nil){
sharedSingletonObj=[[super allocWithZone:NULL]init];
}
else{
NSLog(@”单例对象已经存在!”);
}
}
return sharedSingletonObj;
}
3.对sharedSingletonObj执行了copy,我们需要重写copy方法
-(id)copyWithZone:(NSZone *)zone{
return self;
}
4.对sharedSingletonObj执行了retain,我们需要重写retain方法
-(id)retain{
return self;
}
5.继续对release和autorelease方法进行重写
-(void)release{
}
-(id)autorelease{
return self;
}
6.我们需要实现NSObject里面,关于引用计数API的重写以避免因为引用计数为0导致dealloc的触发
-(NSUInteger)retainCount{
//是一个无限大的int数,避免了系统自动触发单例的dealloc
//也可以明确告知调用者,此为单例对象
return NSUIntegerMax;
}
7.最后,需要通过类方法创建对象转而调用alloc创建,则每次会分配新内存且引用计数+1,显然alloc方法势必也需要重写
+(id)allocWithZone:(NSZone *)zone{
//直接套用sharedsingleton,retain符合alloc管理
//使类方法返回的对象的引用的计数+1,此处retain根据上面的重写内容,不作任何事情
return [[MySingletonClass sharedSingleton]retain];
}
以下是单例模式的全部代码实现
Static MySingletonClass *sharedSingletonObj=nil;
+(MySingletonClass*)sharedSingleton{
@synchronized(self){
//创建
If(sharedSingletonObj==nil){
sharedSingletonObj=[[super allocWithZone:NULL]init];
}
else{
NSLog(@”单例对象已经存在!”);
}
}
return sharedSingletonObj;
}
+(id)allocWithZone:(NSZone *)zone{
return [[MySingletonClass sharedSingleton] retain];
}
-(id)copyWithZone:(NSZone *)zone{
return self;
}
-(id)retain{
return self;
}
-(void)release{
}
-(id)autorelease{
return self;
}
-(NSUInteger)retainCount{
//是一个无限大的int数,避免了系统自动触发单例的dealloc
//也可以明确告知调用者,此为单例对象
return NSUIntegerMax;
}