开发者

How to dealloc and re-initialize a singleton class?

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 oth开发者_Go百科er 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".


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 √


It is very considerable if you don't dealloc the singleton class because it is not advised so till the complete excution of your application. See this for more imformation. To reinitialize your singleton class you need to do the same as you did for the first time.


This solution helped me out. Create a separate method for initializing the class.

@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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜