How to remove and reinitialize a singleton class?

Is it possible to disable a class object?

I have a singleton class "singleton.h" that has one instance, and we can use its properties in any other view controllers.

+(singleton *)sharedMethod{ static singleton *myInstance=nil; if(myInstance ==nil){ myInstance=[[singleton alloc] init]; myInstace.str=@ "hello"; } return myInstance; } 

what I want to know is .., is there a way in which we can exclude a class object in any of our viewControllers ... and then instantiate a new singleton class again .., I tried to do it .., Xcode gives the error message "cannot delete an object of class dealloc".

+6
source share
4 answers

The whole point of a singleton is that you don't release it. Other classes can safely point to a pointer to an instance, so if you want to replace it, you sometimes get strange behavior or even crashes. Therefore, you should not do this.

But this is possible if you did not overwrite the release and retainCount . But your error message quoted seems like you did something on the lines [MyClass release]; which does not work of course.

By the way, you seem to have singleton as the class name. Please try to adhere to the coding rules used by Apple to make your life easier and that of others. Class names must always begin with an uppercase character, method names must always begin with a lowercase character.

+6
source

It is very important if you do not free the singleton class, because it is not recommended until your application is fully retrieved. See more details. To reinitialize your singleton class, you need to do the same thing as you for the first time.

0
source

Decare

 static YOUR_CLASS *shared = nil; static dispatch_once_t oncePredicate; //very important for reinitialize. 

common

 + (instancetype)shared { dispatch_once(&oncePredicate, ^{ shared = [[self alloc] init]; }); return shared; } 

reset

 + (void)reset{ @synchronized(self) { shared = nil; oncePredicate = 0; } } 

you are good to go √

0
source

This solution helped me. Create a separate class initialization method.

 @implementation SomeManager static id sharedManager = nil; + (void)initialize { if (self == [SomeManager class]) { sharedManager = [[self alloc] init]; } } + (id)sharedManager { return sharedManager; } @end 

Source: http://eschatologist.net/blog/?p=178

-1
source

Source: https://habr.com/ru/post/891519/


All Articles