[Sparkle] Singleton initalization
Andy Matuschak
andy at andymatuschak.org
Mon Feb 4 11:11:27 PST 2008
Thanks for catching that, Christiaan. I'm a little confused about your
code in init that checks to see if sharedUpdater is nil; that should
never happen, since alloc gets called before init, and alloc sets the
sharedUpdater pointer (debugger confirms).
I did actually want to restrict the singleton-ness to SUUpdater, not
subclasses, since SUStatusChecker is a subclass of SUUpdater. That
will probably change when I refactor SUStatusChecker, though, since
its design isn't really very good.
Thanks for your help! http://sparkle.andymatuschak.org/changeset/118
- Andy Matuschak
On Feb 4, 2008, at 5:29 AM, Christiaan Hofman wrote:
> There is a serious bug in the current trunk. You never initialize in
> +sharedUpdater. Also, if you'd add the init, it could easily lead to
> excessive initialization, as you always return the shared instance
> without checking if it was ever initialized. Moreover, you'd
> probably always want a singleton, even when the developer wants to
> subclass SUUpdater (the way NSDocumentController works). The design
> could be fixed as follows.
>
>
> static id shareUpdater = nil;
>
> + (id)sharedUpdater {
> if (sharedUpdater == nil)
> [[[self class] alloc] init];
> return sharedUpdater;
> }
>
> - (id)allocWithZone:(NSZone *)zone {
> if (sharedUpdater == nil)
> sharedUpdater = [super allocWithZone:zone];
> else
> [sharedUpdater retain];
> return sharedUpdater;
> }
>
> - (id)init {
> if (self = [super init]) {
> if (sharedUpdater == nil) {
> [self setHostBundle:[NSBundle mainBundle]];
> [[NSNotificationCenter defaultCenter] addObserver:self
> selector:@selector(applicationDidFinishLaunching:)
> name:NSApplicationDidFinishLaunchingNotification object:NSApp];
> } else if (self != sharedUpdater) {
> // this should never happen
> [self release];
> self = [sharedUpdater retain];
> }
> }
> return self;
> }
>
> Instead of the extra retains of the sharedUpdater, you can also
> override -retain, -release, -autorelease. Either one is required, or
> your sharedUpdater may get over-released at some point.
>
> Christiaan
>
More information about the Sparkle
mailing list