1、内存管理
  • 1.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;
  • 1.2 处理ARC和MRC,对象释放

/** 使用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、单例
  • 2.1 单例(合并)


#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; \
}

  • 2.2 单例(分开)

#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;\
}



作者: CH520