2

I have a factory which handles singletons as follows

@implementation MyFactory

- (AudioEngine *)theAudioEngine 
{
    static AudioEngine *ae = nil;
    if (ae == nil) {
        ae = [[AudioEngine] alloc] init];
    }
    return ae;
}

@end

Are such static local variables released when the MyFactory instance is dealloc'ed?

Hari Honor
  • 8,677
  • 8
  • 51
  • 54

2 Answers2

3

No they are not released. You could however move the variable to the heap and have a class method to release it, which is itself called from some app-level closedown method:

static AudioEngine *_ae = nil;

@implementation MyFactory

- (AudioEngine *)theAudioEngine 
{
    if (_ae == nil) {
        _ae = [[AudioEngine] alloc] init];
    }
    return _ae;
}

+ (void)cleanup
{
    if (_ae != nil)
    {
        // No need to release when in ARC mode (thanks to @AndrewMadsen)
        //[_ae release];
        _ae = nil;
    }
}

@end
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • Of course, with ARC `[_ae release]` is prohibited, but `_ae = nil` is sufficient to release the instance (assuming no other objects have a strong reference to it). – Andrew Madsen Oct 29 '12 at 15:37
1

As stated by @trojanfoe the answer is no, presumably because the compiler allocates a permanent space for the static var and being also a local var, only the method itself would ever have access to it and thus the ability to dealloc it (via = nil).

Another strategy which works presuming your factory is an instance object and not a static class:

@implementation MyFactory
{
    AudioEngine *_audioEngine;
}

- (AudioEngine *)audioEngineSingleton
{
    if (_audioEngine == nil) {
        _audioEngine = [[AudioEngine alloc] init];
    }

    return _audioEngine;
}

@end

When your MyFactory instance dealloc's so will the ivars.

Hari Honor
  • 8,677
  • 8
  • 51
  • 54
  • Singh is King. Nice explanation, but i believe dealloc method never gets called for singleton, specially in case of Factory implementation given above – iHS Dec 10 '12 at 21:54
  • MyFactory is not a singleton itself. Nor is it meant to be a static class. You create an instance at the beginning of your app, and when that instance is nil'ed on shutdown it will dealloc and release its ivars (which *are* singletons). – Hari Honor Dec 11 '12 at 07:18