Note that there are some explanatory texts on larger screens.

plurals
  1. POElegant and 'correct' multiton implementation in Objective C?
    text
    copied!<p>Would you call this implementation of a multiton in objective-c 'elegant'? I have programmatically 'disallowed' use of <code>alloc</code> and <code>allocWithZone:</code> because the decision to allocate or not allocate memory needs to be done based on a key.</p> <p>I know for sure that I need to work with only two instances, so I'm using 'switch-case' instead of a map.</p> <pre><code>#import "Multiton.h" static Multiton *firstInstance = nil; static Multiton *secondInstance = nil; @implementation Multiton + (Multiton *) sharedInstanceForDirection:(enum KeyName)direction { return [[self allocWithKey:direction] init]; } + (id) allocWithKey:(enum KeyName)key { return [self allocWithZone:nil andKey:key]; } + (id) allocWithZone:(NSZone *)zone andKey:(enum KeyName)key { Multiton **sharedInstance; @synchronized(self) { switch (key) { case KEY_1: sharedInstance = &amp;firstInstance; break; case KEY_2: sharedInstance = &amp;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; } @end </code></pre> <p>PS: I've not tried out if this works as yet, but its compiling cleanly :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload