提要:單例設計模式需要重寫父類的方法。因為全局實例不允許釋放,所以和內存管理相關的retain,release,autorelease方法均需要重寫,重寫的目的就是避免對這個實例的內存方面進行操作,防止引用計數發生變化。
單例模式具體實例代碼如下:
SingletonTeather.h文件
#import
@interface SingletonTeather : NSObject
@property (nonatomic,strong) NSString *name;
//@property (nonatomic,assign) NSInteger age;
@property (nonatomic,strong) NSMutableDictionary *info;
+(SingletonTeather *)getSingletonTeather;
@end
SingletonTeather.c文件
#import SingletonTeather.h
staticSingletonTeather *shareSingletonTeather = nil;
@implementation SingletonTeather
@synthesize name,info;
+(SingletonTeather *)getSingletonTeather
{
if (shareSingletonTeather == nil) {
shareSingletonTeather = [[SingletonTeatheralloc]init];
}
return shareSingletonTeather;
}
+(id)allocWithZone:(struct_NSZone *)zone
{
if (shareSingletonTeather == nil) {
shareSingletonTeather = [[superallocWithZone:zone]init];
}
return shareSingletonTeather;
}
-(id)copyWithZone:(struct_NSZone *)zone
{
return self;
}
-(NSUInteger)retainCount
{
return NSIntegerMax;
}
-(id)retain
{
return self;
}
-(onewayvoid)release
{
}
-(id)autorelease
{
return self;
}
@end