简体   繁体   中英

Singleton class in objective c

I have create a SinglestonClass in my code but i have a problem. My variable are initialized in the -init method but when i call the singlestonClass these variable are re-initialize. Can you help me for create a single initialization for my variable? thanks.

@implementation SingletonController

@synthesize arrayPosition;
@synthesize arrayMovement;

@synthesize actualPosition;
@synthesize actualMove;

@synthesize stopThread;


+(SingletonController*)sharedSingletonController{

    static SingletonController *sharedSingletonController;

    @synchronized(self) {
        if(!sharedSingletonController){
            sharedSingletonController = [[SingletonController alloc]init];
        }
    }

    return sharedSingletonController;
}


//I don't want a re-initialization for these variables
-(id)init{
    self = [super init];
    if (self != nil) {
        arrayPosition = [[NSMutableArray alloc]init];
        arrayMovement = [[NSMutableArray alloc]init];

        actualPosition = [[Position alloc]init];
        actualMove = [[Movement alloc]init];

        stopThread = FALSE;
    }
    return self;
}


-(void) dealloc {
    [super dealloc];
}
@end

Your init method should not be called by anyone except for your singleton class itself. That's what the sharedSingletonController method is for. This is your factory method that is responsible for returning the same static instance of your class. I'd also suggest that you rename the static instance of your singleton object and/or the sharedSingletonController selector itself to disambiguate between the two and for cleaner design. In this particular case, it may confuse someone who has to read your code.

Without seeing how the client code is calling on your singleton factory method, it's difficult to decipher where your problem is. We'd need to see the rest of the code including how it's being called. In your client code, you should be using something such as:

SingletonController *sigController = [SingletonController sharedSingletonController];

DO NOT DO:

SingletonController *sigController = [[SingletonController alloc] init];

Read here for more information in the Cocoa Fundamentals Guide.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM