I have created singleton object, at one point of time have to release the singleton object. How to release the singleton object in non-ARC and ARC?
Asked
Active
Viewed 1,585 times
1
-
http://www.galloway.me.uk/tutorials/singleton-classes/ – User1075 Apr 24 '15 at 12:39
-
look under non arc code in the link i provided – User1075 Apr 24 '15 at 12:39
-
- (oneway void)release { // never release } how we can use this method ? – Jaico Varghese Apr 24 '15 at 12:54
-
1If you want to release it, 99.99% of the time that means you *shouldn't make it a singleton*. Can you explain your use case? – Tommy Apr 24 '15 at 12:58
-
for eg: i created one label instance and after some time have to release the object. – Jaico Varghese Apr 24 '15 at 13:07
-
You don't release a singleton object. Ever. If you want to release it, it isn't a singleton. – gnasher729 Apr 24 '15 at 13:12
-
Having one Label instance, isn't a reason to have a singleton. Singleton you make to assure there will never be any other instance of that class. Just one. In your case, just don't make it a singleton. However, the answers here are valid, provided you never want to have another label object again, once you disposed of it. – Motti Shneor Feb 02 '22 at 10:27
2 Answers
1
If you put the single instance as a global variable of the class, for example:
static MyClass *_instance = nil;
instead of being static
local within the sharedInstance
class method, then you can create a destroy method like this:
+ (void)destroyInstance
{
_instance = nil;
}
However one issue I can see is the use of the dispatch_once_t
that is commonly used to ensure atomic initialization; I think you would need to avoid using it in this case as it's not possible to reset it. This might not be an issue if you never intend to call sharedInstance
again, once it's been destroyed.

trojanfoe
- 120,358
- 21
- 212
- 242
0
@interface MySingleton : NSObject
static dispatch_once_t predicate;
static MySingleton *sharedSingletonInstance = nil;
@implementation MySingleton
+ (MySingleton *)ShareInstance {
dispatch_once(&predicate, ^{
sharedSingletonInstance = [[self alloc] init];
});
return sharedSingletonInstance;
}
+ (void)destroyMySingletonInstance {
sharedSingletonInstance = nil;
predicate = 0;
}
- (void)dealloc {
NSLog(@"------");
}
// TODO
...
@end