Completely release singleton Objective-C

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?

+5
source share
7 answers

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 . , .

+6

, singleton

Objective-C. , , , , . -, .

, , A S1 S. A S1, S1 , S , , . , S2, S, S1 S2. , .

, , -retain , , swizzling -release, , .

reset , . - (, ) , , , . , .

+5

, - ( ), . . . .

, . , , , . , self . . . .

, , . , , , , , ( sharedInstance).

, ; , .

, . .

+5

. : [MyClass killSingleton]; nil. , - [MyClass sharedSingleton], , , .

EDIT: , release . , - , 1 . , ivar ( ARC), , . , .

+3

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
+1
//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
0

I needed to clear singleton, so I ended up doing the following:

- (void)deleteSingleton{
@synchronized(self) {
    if (sharedConfigSingletone != nil) {
        sharedConfigSingletone = nil;
    }
}
}

Hope this helps.

0
source

All Articles