我的单例访问器方法通常是以下的一些变体:
static MyClass *gInstance = NULL;
+ (MyClass *)instance
{
@synchronized(self)
{
if (gInstance == NULL)
gInstance = [[self alloc] init];
}
return(gInstance);
}
Run Code Online (Sandbox Code Playgroud)
我可以做些什么来改善这个?
嘿伙计们 - 我正在写一个非常简单的iPhone应用程序.数据来自plist文件(基本上是NSDictionary),我正在尝试加载到单例类中,并使用我的各种视图控制器来访问数据.
这是我的单例的实现(在此线程之后重新建模)
@implementation SearchData
@synthesize searchDict;
@synthesize searchArray;
- (id)init {
if (self = [super init]) {
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"searches.plist"];
searchDict = [NSDictionary dictionaryWithContentsOfFile:finalPath];
searchArray = [searchDict allKeys];
}
return self;
}
- (void)dealloc {
[searchDict release];
[searchArray release];
[super dealloc];
}
static SearchData *sharedSingleton = NULL;
+ (SearchData *)sharedSearchData {
@synchronized(self) {
if (sharedSingleton == NULL)
sharedSingleton = [[self alloc] init];
}
return(sharedSingleton);
}
@end
Run Code Online (Sandbox Code Playgroud)
所以每当我尝试访问我的应用程序中的其他地方的searchDict或searchArray属性时(如TableView委托),如下所示:
[[[SearchData …Run Code Online (Sandbox Code Playgroud)