Skip to content

Instantly share code, notes, and snippets.

@griotspeak
Created August 17, 2016 19:10
Show Gist options
  • Save griotspeak/fa93c5d9f70393c7fc5dec9d034195fb to your computer and use it in GitHub Desktop.
Save griotspeak/fa93c5d9f70393c7fc5dec9d034195fb to your computer and use it in GitHub Desktop.
Designated initializers
//
// GalacticKnight.h
// MoreMessage
//
// Created by TJ Usiyan on 2016/17/08.
// Copyright © 2016 Buttons and Lights LLC. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Person.h"
@interface GalacticKnight : Person {
NSString *_galaxy;
}
- (instancetype)initWithName:(NSString *)name
galaxy:(NSString *)galaxy NS_DESIGNATED_INITIALIZER;
- (NSString *)galaxy;
@end
//
// GalacticKnight.m
// MoreMessage
//
// Created by TJ Usiyan on 2016/17/08.
// Copyright © 2016 Buttons and Lights LLC. All rights reserved.
//
#import "GalacticKnight.h"
@implementation GalacticKnight
- (instancetype)initWithName:(NSString *)name
galaxy:(NSString *)galaxy {
self = [super initWithName:name];
if (self) {
_galaxy = galaxy;
}
return self;
}
- (instancetype)initWithName:(NSString *)name {
return [self initWithName:name
galaxy:@"Unknown"];
}
- (NSString *)galaxy {
return _galaxy;
}
@end
//
// main.m
// MoreMessage
//
// Created by TJ Usiyan on 2016/17/08.
// Copyright © 2016 Buttons and Lights LLC. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "GalacticKnight.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
GalacticKnight *person = [[GalacticKnight alloc] initWithName:@"Elizabeth"
galaxy:@"Andromeda"];
NSLog(@"Hi, my name is %@", person);
NSLog(@"I am from the galaxy %@", [person galaxy]);
}
return 0;
}
//
// Person.h
// MoreMessage
//
// Created by TJ Usiyan on 2016/17/08.
// Copyright © 2016 Buttons and Lights LLC. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Person : NSObject {
NSString *_name;
}
- (instancetype)initWithName:(NSString *)name NS_DESIGNATED_INITIALIZER;
- (NSString *)name;
@end
//
// Person.m
// MoreMessage
//
// Created by TJ Usiyan on 2016/17/08.
// Copyright © 2016 Buttons and Lights LLC. All rights reserved.
//
#import "Person.h"
@implementation Person
- (instancetype)init {
return [self initWithName:@"Unnamed"];
}
- (instancetype)initWithName:(NSString *)name {
self = [super init];
if (self) {
_name = name;
}
return self;
}
- (NSString *)name {
return _name;
}
- (NSString *)description {
return _name;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment