最近我在用Xcode 静态分析器时发现我所有单实例代码中的
+(id)allocWithZone:(NSZone *)zone
都有警告:
Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected
意思是allocWithZone返回的object必须是retain+1的,而单实例中的-(release)是直接返回self的,所以没有retain。
我记得以前版本的Xcode中是没有这个提示的,我不知道是不是有别的实现方法了吗?
我现在的写法类似下面这样:
@implementation MySingleton
static MySingleton *sSharedSingleton = nil;
+ (MySingleton *)sharedSingleton
{
if (sSharedSingleton == nil)
{
sSharedSingleton = [[super allocWithZone:NULL] init];
}
return sSharedSingleton;
}
+ (id)allocWithZone:(NSZone *)zone
{
return [[self sharedSingleton] retain];
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return NSUIntegerMax; //denotes an object that cannot be released
}
- (oneway void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
@end
+(id)allocWithZone:(NSZone *)zone
都有警告:
Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected
意思是allocWithZone返回的object必须是retain+1的,而单实例中的-(release)是直接返回self的,所以没有retain。
我记得以前版本的Xcode中是没有这个提示的,我不知道是不是有别的实现方法了吗?
我现在的写法类似下面这样:
@implementation MySingleton
static MySingleton *sSharedSingleton = nil;
+ (MySingleton *)sharedSingleton
{
if (sSharedSingleton == nil)
{
sSharedSingleton = [[super allocWithZone:NULL] init];
}
return sSharedSingleton;
}
+ (id)allocWithZone:(NSZone *)zone
{
return [[self sharedSingleton] retain];
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return NSUIntegerMax; //denotes an object that cannot be released
}
- (oneway void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
@end