Let’s say you are programming a flashcard app. In the model for these flashcards, you will have a flashcard object, and each flashcard has 2 strings as properties (one for the front of the card, and one for the back). You could just alloc-init the card, and then set them later… but what use is a blank flashcard? Why not only initialize a flashcard when those piece of data are provided? That is what custom initializers are for.
Here is an example of making this flashcard class with its own custom initializer.
In FlashCard.h:
@interface FlashCard : NSObject
@property (strong, nonatomic) NSString *frontText;
@property (strong, nonatomic) NSString *backText;
- (instancetype)initWithFront:(NSString *)onFront back:(NSString *)onBack;
@end
In FlashCard.m:
#import "FlashCard.h"
@implementation FlashCard
- (instancetype)initWithFront:(NSString *)onFront back:(NSString *)onBack
{
if ((self = [super init])) {
_frontText = onFront;
_backText = onBack;
}
return self;
}
@end
And that is pretty much all there is to it. While it is not a lot of text, there are a few things that I had to look up a bit to understand what was going on in these statements, so I will go into more depth to explain some of the new things shown here.