Skip to content

Instantly share code, notes, and snippets.

@timothyekl
Created September 18, 2013 04:17
Show Gist options
  • Save timothyekl/6604488 to your computer and use it in GitHub Desktop.
Save timothyekl/6604488 to your computer and use it in GitHub Desktop.
Abstract superclass initializers in Objective-C
#import <Foundation/Foundation.h>
@interface Parent : NSObject
@end
@implementation Parent
- (id)init;
{
if (!(self = [super init]))
return nil;
if ([self class] == [Parent class]) {
[NSException raise:@"Instantiate a subclass!" format:nil];
return nil;
}
return self;
}
- (NSString *)description;
{
return [NSString stringWithFormat:@"<%@:%p>", NSStringFromClass([self class]), self];
}
@end
@interface Child : Parent
@end
@implementation Child
- (id)init;
{
if (!(self = [super init]))
return nil;
return self;
}
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
Child *child = [[Child alloc] init];
NSLog(@"%@", [child description]);
Parent *parent = [[Parent alloc] init];
NSLog(@"%@", [parent description]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment