好的,appDev,你可能会在网上找到很多不同的技术来实现这一点.然而,对于iOS应用程序开发,我认为最方便的方法是执行以下操作:
编写获取singleton对象的方法.(建议:使用dispatch_once
线程和GCD).
将方法包装在宏中,并将其添加到$Project$-Prefix.pch
文件中.
每当需要类的单例对象时,调用单行宏.
例子:
CommonMacros.h:
#define SINGLETON_FOR_CLASS(classname)
+ (id) shared##classname {
static dispatch_once_t pred = 0;
static id _sharedObject = nil;
dispatch_once(&pred, ^{
_sharedObject = [[self alloc] init];
});
return _sharedObject;
}
YourProject-Prefix.pch:
...
#import "CommonMacros.h"
...
YourSingletonClass.m:
...
SINGLETON_FOR_CLASS(YourSingletonClass)
...