I am new to writing singletones and I have to use it for the current iOS project. One of the requirements is that it can be killed. I know this goes against the design of the singleton, but is it something that needs / can be done?
Of course, this can be done, but if you are looking for an object that can be created and then released when it is not needed ... it sounds like an ordinary object. :)
, . , (, , , ), .
, , singleton , (, ). , , , singleton "" , singleton.
- , singleton (- ), , . , , , .
, , , singleton . , .
, singleton
Objective-C. , , , , . -, .
, , A S1 S. A S1, S1 , S , , . , S2, S, S1 S2. , .
, , -retain , , swizzling -release, , .
-retain
-release
reset , . - (, ) , , , . , .
, - ( ), . . . .
, . , , , . , self . . . .
self
, , . , , , , , ( sharedInstance).
sharedInstance
, ; , .
, . .
. : [MyClass killSingleton]; nil. , - [MyClass sharedSingleton], , , .
EDIT: , release . , - , 1 . , ivar ( ARC), , . , .
release
Singleton, ARC
//ARC @interface Singleton : NSObject + (Singleton *)sharedInstance; + (void)selfDestruct; @end @implementation Singleton static Singleton *sharedInstance = nil; + (Singleton *)sharedInstance { if (sharedInstance == nil) { sharedInstance = [[Singleton alloc] init]; } return sharedInstance; } + (void) selfDestruct { sharedInstance = nil; } @end
//This can be implemented using bool variable. If bool no create new instance. @interface Singleton : NSObject + (Singleton *)sharedInstance; @end @implementation Singleton static Singleton *sharedInstance = nil; + (Singleton *)sharedInstance { if (!keepInstance) { sharedInstance = [[Singleton alloc] init]; keepInstance = YES; } return sharedInstance; } @end
I needed to clear singleton, so I ended up doing the following:
- (void)deleteSingleton{ @synchronized(self) { if (sharedConfigSingletone != nil) { sharedConfigSingletone = nil; } } }
Hope this helps.