在 Objective-C 中,如何使用 ARC 编写单例?在ARC中,不允许覆盖release、autorelease、retain、retainCount方法,如何避免一个对象被释放?我知道没有 ARC,一个经典的单身人士会喜欢下面:
@interface SingletonObject
+ (SingletonObject*)sharedObject;
@end
SingletonObject *sharedObj;
@implementation SingletonObject
+ (id)allocWithZone:(NSZone *)zone
{
if (sharedObj == nil) {
//So the code [[SingletonObject alloc] init] is equal with [SingletonObject sharedObject]
sharedObj = [super allocWithZone:zone];
}
return sharedObj;
}
+ (void)initialize
{
if (self == [SingletonObject class]) {
sharedObj = [[SingletonObject alloc] init];
}
}
+ (SingletonObject*)sharedObject
{
return sharedObj;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return UINT_MAX; //denotes an object that cannot be released
}
- (oneway void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
- (id)init {
self = [super init];
if (self) {
//...
}
return self;
}
@end
仅删除保留、保留计数、释放、自动释放方法是否安全?谢谢!