0

So I have a singleton in Objective-C, there's one static method exposed to access the one and only instance:

+ (id)sharedMyClass {
    static MyClass* sharedMyClass = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedMyClass = [[self alloc] init];
        sharedMyClass.myStringProperty = @"bla"; // here
    });
    return sharedMyClass;
}

and a non-exposed init method, used only when the instance is first created:

- (id)init {
    if (self = [super init]) {
        self.myStringProperty = @"bla"; // or here
        return self;
    }
    return nil;
}

I can initialize the instance's properties in the first method, by setting them directly on sharedMyClass within the dispatch_once block. Or I can set them on self in the init method. I know functionally there isn't any difference, but is there a convention for this? What's the best practice?

2 Answers 2

4

Setting them in -init is better. You might someday wish to make this a non-singleton (for example, scoped to user session), or a "hybrid" singleton (NSUserDefaults has a "singleton-like" member but you can also create arbitrary instances). If setup is done in -init, you won't need to change as much for this.

0

I always initialise them in the +shared method. And then it gets more and more and I add an -init method and kick myself because I should have done that in the first place. Either do it like me, or better start with the init method in the first place.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.