内存管理、单例
原创
©著作权归作者所有:来自51CTO博客作者wx6103b5205e184的原创作品,请联系作者获取转载授权,否则将追究法律责任
1、内存管理
/** 定义一个define函数 */
#define TT_RELEASE_CF_SAFELY(__REF) { if (nil != (__REF)) { CFRelease(__REF); __REF = nil; } }
/** 强引用、弱引用 */
#define CHWeakSelf(type) __weak typeof(type) weak##type = type;
#define CHStrongSelf(type) __strong typeof(type) type = weak##type;
/** 使用ARC和不使用ARC */
#if __has_feature(objc_arc)
//compiling with ARC
#else
// compiling without ARC
#endif
/** 释放一个对象 */
#define SAFE_DELETE(P) if(P) { [P release], P = nil; }
2、单例
#define SYNTHESIZE_SINGLETON_FOR_CLASS(classname) \
\
static classname *shared##classname = nil; \
\
+ (classname *)shared##classname \
{ \
@synchronized(self) \
{ \
if (shared##classname == nil) \
{ \
shared##classname = [self alloc] init]; \
} \
} \
\
return shared##classname; \
} \
\
+ (id)allocWithZone:(NSZone *)zone \
{ \
@synchronized(self) \
{ \
if (shared##classname == nil) \
{ \
shared##classname = [super allocWithZone:zone]; \
return shared##classname; \
} \
} \
\
return nil; \
} \
\
- (id)copyWithZone:(NSZone *)zone \
{ \
return self; \
}
#pragma mark 接口.h
#define singleton_interface(className) +(className *)shared##className;
#pragma mark 实现.m
#define singleton_implementation(className) \
static className *_instance;\
+(id)shared##className{\
if(!_instance){\
_instance=[[self alloc]init];\
}\
return _instance;\
}\
+(id)allocWithZone:(struct _NSZone *)zone{\
static dispatch_once_t dispatchOnce;\
dispatch_once(&dispatchOnce, ^{\
_instance=[super allocWithZone:zone];\
});\
return _instance;\
}