objective_C Creating a Singleton Instance

官网Creating a singleton instance有介绍如何创建单一实例.没时间翻译,大家看看代码就知道了:

static MyGizmoClass *sharedGizmoManager = nil; + (MyGizmoClass*)sharedManager { if (sharedGizmoManager == nil) { sharedGizmoManager = [[super allocWithZone:NULL] init]; } return sharedGizmoManager; } + (id)allocWithZone:(NSZone *)zone { return [[self sharedManager] retain]; } - (id)copyWithZone:(NSZone *)zone { return self; } - (id)retain { return self; } - (NSUInteger)retainCount { return NSUIntegerMax; //denotes an object that cannot be released } - (void)release { //do nothing } - (id)autorelease { return self; } //调用方法: MyGizmoClass *instance = [MyGizmoClass sharedManager]; 

这只适用于单线程,如果想在多线程中用到singleton instance,如何办呢。 在此blog中有方法介绍。说得很清楚明了,一看代码就明白了。

你可能感兴趣的:(多线程,c,object,Blog,null)