Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 38 ยท Objects and Classes

Initializers and dealloc

Learn how to write init methods correctly, the designated initializer pattern, convenience initializers and factory methods, description overrides, and dealloc.

alloc gives you raw, zeroed memory; init makes it a usable object. Writing initializers properly matters, because a half-initialized object leads to subtle bugs, and because subclasses depend on a predictable chain of calls. This lesson covers the init template, designated and convenience initializers, factory methods, description, and the cleanup method dealloc.

The init template

Every initializer follows the same shape:

OBJECTIVEC
- (instancetype)init {
    self = [super init];
    if (self) {
        _name = @"Unnamed";
        _age = 0;
    }
    return self;
}
  1. Call the superclass initializer and assign the result to self. A superclass may return a different object (class clusters do), or nil on failure.
  2. Only if self is non-nil, set up your instance variables.
  3. Return self.

The return type is instancetype, which means "an instance of the receiving class", so subclasses get the right type automatically. Older code writes id.

Inside init use the instance variables directly (_name = ...) instead of the property accessors. Subclasses may override setters in ways that assume the object is fully built.

Initializers with parameters

By convention they start with init:

OBJECTIVEC
- (instancetype)initWithName:(NSString *)name age:(NSInteger)age {
    self = [super init];
    if (self) {
        _name = [name copy];
        _age = age;
    }
    return self;
}

Use it like this:

OBJECTIVEC
Person *p = [[Person alloc] initWithName:@"Ada" age:36];

Designated and convenience initializers

A class should have one designated initializer: the one that does the full setup and calls the superclass's designated initializer. Other initializers are convenience initializers that delegate to it with self:

OBJECTIVEC
- (instancetype)initWithName:(NSString *)name age:(NSInteger)age {   // designated
    self = [super init];
    if (self) { _name = [name copy]; _age = age; }
    return self;
}

- (instancetype)initWithName:(NSString *)name {                       // convenience
    return [self initWithName:name age:0];
}

- (instancetype)init {                                                // convenience
    return [self initWithName:@"Unnamed"];
}

The rules:

  1. The designated initializer calls [super designatedInitializer].
  2. Convenience initializers call [self anotherInitializer] and end up at the designated one.
  3. If your designated initializer differs from the superclass's, override the superclass's designated initializer and point it to yours, so the inherited init cannot create an invalid object.

Mark the designated initializer so that the compiler enforces it:

OBJECTIVEC
- (instancetype)initWithName:(NSString *)name age:(NSInteger)age NS_DESIGNATED_INITIALIZER;
- (instancetype)init NS_UNAVAILABLE;      // forbid plain init

Factory methods

Class methods that return ready objects are named after the class:

OBJECTIVEC
+ (instancetype)personWithName:(NSString *)name age:(NSInteger)age {
    return [[self alloc] initWithName:name age:age];
}

Use [self alloc], not [Person alloc], so subclasses get the right class. Cocoa has many: [NSString stringWithFormat:], [NSArray arrayWithObject:], [NSDate date].

Failable initializers

An initializer can return nil when the arguments are invalid:

OBJECTIVEC
- (instancetype)initWithAge:(NSInteger)age {
    if (age < 0) { return nil; }
    self = [super init];
    if (self) { _age = age; }
    return self;
}

Document this and mark the return nullable. Under ARC, returning nil before calling super init is fine.

description and debugging

Override description to control what %@ and the debugger print:

OBJECTIVEC
- (NSString *)description {
    return [NSString stringWithFormat:@"<%@: %@, %ld>",
            NSStringFromClass([self class]), _name, (long)_age];
}

dealloc

dealloc runs once when the object's last owner releases it. Use it to release resources that ARC does not manage: observers, timers, C memory, file descriptors, notification registrations.

OBJECTIVEC
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    free(_buffer);          // a malloc'ed C buffer
    // no [super dealloc] under ARC: the compiler adds it
}

Under ARC you never call dealloc yourself and never call [super dealloc] (that is a compile error). ARC releases the object-typed ivars for you. Do not use self in ways that revive the object, do not use properties with side effects in dealloc, and keep it short.

Stand-in: the init chain

This C model builds the same chain: a base "class" init, a subclass init that calls it, a convenience initializer with defaults, and a "dealloc" that frees resources.

C Stand-in (C): designated and convenience initializers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Stand-in: factory function and description

C Stand-in (C): factory and a description function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Common mistakes

  • Forgetting self = [super init]; or returning without return self;.
  • Doing work outside the if (self) block.
  • Using property setters in init or dealloc.
  • Calling [super dealloc] under ARC.
  • Making a convenience initializer call super instead of self.
  • Leaving the inherited init available when it creates an invalid object.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a convenience initializer call?

    Convenience initializers delegate with self so that the designated initializer always runs.
  2. 2. Which return type should an initializer use?

    instancetype means an object of the receiver's class.
  3. 3. What should you do inside dealloc under ARC?

    ARC releases objects and adds the super call. You clean up external resources.
  4. 4. Why use [self alloc] in a factory method?

    In a class method self is the class that received the message, so subclasses are respected.

Summary

  • Initializers follow self = [super init]; if (self) { ... } return self;.
  • One designated initializer does the full setup; convenience initializers delegate to it with self.
  • Factory class methods use [[self alloc] initWith...].
  • Override description for readable logs.
  • dealloc cleans up non-ARC resources; never call [super dealloc] under ARC.

Next: Inheritance and Polymorphism