Elegant and 'correct' multiton implementation in Objective C?

Posted by submachine on Stack Overflow See other posts from Stack Overflow or by submachine
Published on 2010-03-24T11:48:07Z Indexed on 2010/03/24 11:53 UTC
Read the original article Hit count: 214

Would you call this implementation of a multiton in objective-c 'elegant'? I have programmatically 'disallowed' use of alloc and allocWithZone: because the decision to allocate or not allocate memory needs to be done based on a key.

I know for sure that I need to work with only two instances, so I'm using 'switch-case' instead of a map.

#import "Multiton.h"

static Multiton *firstInstance = nil;
static Multiton *secondInstance = nil;

@implementation Multiton

+ (Multiton *) sharedInstanceForDirection:(char)direction {

    return [[self allocWithKey:direction] init];
}

+ (id) allocWithKey:(char)key {

    return [self allocWithZone:nil andKey:key];
}

+ (id)allocWithZone:(NSZone *)zone andKey:(char)key {

    Multiton **sharedInstance;

    @synchronized(self) {

        switch (key) {
            case KEY_1:
                sharedInstance = &firstInstance;
                break;
            case KEY_2:
                sharedInstance = &secondInstance;
                break;
            default:
                [NSException raise:NSInvalidArgumentException format:@"Invalid key"];
                break;
        }
        if (*sharedInstance == nil)
            *sharedInstance = [super allocWithZone:zone];
    }

    return *sharedInstance;
}

+ (id) allocWithZone:(NSZone *)zone {

    //Do not allow use of alloc and allocWithZone
    [NSException raise:NSObjectInaccessibleException format:@"Use allocWithZone:andKey: or allocWithKey:"];
    return nil;
}

- (id) copyWithZone:(NSZone *)zone {

    return self;
}

- (id) retain {

    return self;
}

- (unsigned) retainCount {

    return NSUIntegerMax;
}

- (void) release {

    return;
}

- (id) autorelease {

    return self;
}

- (id) init {
    [super init];
    return self;
}

PS: I've not tried out if this works as yet, but its compiling cleanly :)

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about multiton