Is it possible to dealloc a class object ?
I have a singleton class "singleton.h" which has a single instance and we can make use of 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 any way by which we can dealloc the class object in any of our viewControllers...and then again creat an instance of a new singleton class.., I tried doing so.., Xcode throws an error "cannot dealloc class object".
If you have a regular object that you can't deinitialize it's a memory problem. Singletons are no different, except that you have to write a function to do it. Singletons have to be completely self managed. This means from init to deinit.
Using this new definition of the singleton, you can write a clear method that can be called by any of the classes initialized with the Singleton metaclass and it will clear the _instance attribute. So in your case, MyClass. clear() would reset the _instance attribute to None.
We can distinguish a Singleton class from the usual classes with respect to the process of instantiating the object of the class. To instantiate a normal class, we use a java constructor. On the other hand, to instantiate a singleton class, we use the getInstance() method.
If you really need to reset a singleton instance (which doesn't makes much sense actually) you could wrap all its inner members in a private object, and reinitialize via an explicit initialize() and reset() methods. That way, you can preserve your singleton istance and provide some kind of "reset" functionality.
The whole point of a singleton is that you do not deallocate it ever. Other classes may safe a pointer to the instance, so if you want to replace it you'd get strange behavior or even crashes sometimes. So you shouldn't do it.
But it is possible, as long as you haven't overwritten the release
and retainCount
methods. But your cited error message seems to suggest you've done something along the lines of [MyClass release];
which doesn't work, of course.
BTW, you seem to have singleton
as a class name. Please try to stick to the coding conventions used by Apple to make your life and that of other people easier. Class names should always start with an uppercase character, method names should always start with a lowercase character.
declare
static YOUR_CLASS *shared = nil;
static dispatch_once_t oncePredicate; //very important for reinitialize.
use instance
+ (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 √
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With