宏定义 object-c 单例
2012-10-19 14:30 三戒1993 阅读(89) 评论(0) 编辑 收藏 举报今天发现单例用宏来声明 确实很实用,所以记录下来
#define GTMOBJECT_SINGLETON_BOILERPLATE(_object_name_, _shared_obj_name_)
static _object_name_ *z##_shared_obj_name_ = nil;
+ (_object_name_ *)_shared_obj_name_ {
@synchronized(self) {
if (z##_shared_obj_name_ == nil) {
/* Note that ‘self’ may not be the same as _object_name_ */
/* first assignment done in allocWithZone but we must reassign in case init fails */
z##_shared_obj_name_ = [[self alloc] init];
_GTMDevAssert((z##_shared_obj_name_ != nil), @”didn’t catch singleton allocation”);
}
}
return z##_shared_obj_name_;
}
+ (id)allocWithZone:(NSZone *)zone {
@synchronized(self) {
if (z##_shared_obj_name_ == nil) {
z##_shared_obj_name_ = [super allocWithZone:zone];
return z##_shared_obj_name_;
}
}
/* We can’t return the shared instance, because it’s been init’d */
_GTMDevAssert(NO, @”use the singleton API, not alloc+init”);
return nil;
}
- (id)retain {
return self;
}
- (NSUInteger)retainCount {
return NSUIntegerMax;
}
- (void)release {
}
- (id)autorelease {
return self;
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}