Skip to content

Instantly share code, notes, and snippets.

@aprato
Forked from steipete/Macros.h
Created March 11, 2014 17:06
Show Gist options
  • Save aprato/9490262 to your computer and use it in GitHub Desktop.
Save aprato/9490262 to your computer and use it in GitHub Desktop.
#ifndef NS_DESIGNATED_INITIALIZER
#if __has_attribute(objc_designated_initializer)
#define NS_DESIGNATED_INITIALIZER __attribute((objc_designated_initializer))
#else
#define NS_DESIGNATED_INITIALIZER
#endif
#endif
@aprato
Copy link
Author

aprato commented Mar 11, 2014

From my still open tab...

In Objective-C, object initialization is based on the notion of a designated initializer, an initializer method that is responsible for calling one of its superclass’s initializers and then initializing its own instance variables. Initializers that are not designated initializers are known as secondary initializers. Secondary initializers typically delegate to another initializer—eventually terminating the chain at a designated initializer—rather than performing initialization themselves.

The designated initializer pattern helps ensure that inherited initializers properly initialize all instance variables. A subclass that needs to perform nontrivial initialization should override all of its superclass’s designated initializers, but it does not need to override the secondary initializers. For more information about initializers, see “Object Initialization”.

To clarify the distinction between designated and secondary initializers clear, you can add the NS_DESIGNATED_INITIALIZER macro to any method in the init family, denoting it a designated initializer. Using this macro introduces a few restrictions:

  • The implementation of a designated initializer must chain to a superclass init method (with [super init...]) that is a designated initializer for the superclass.
  • The implementation of a secondary initializer (an initializer not marked as a designated initializer within a class that has at least one initializer marked as a designated initializer) must delegate to another initializer (with [self init...]).
  • If a class provides one or more designated initializers, it must implement all of the designated initializers of its superclass.

If any of these restrictions are violated, you receive warnings from the compiler.

@aprato
Copy link
Author

aprato commented Mar 11, 2014

How to Adopt

Identify designated initializers in your classes, and tag them with the NS_DESIGNATED_INITIALIZER macro. For example:

- (instancetype)init NS_DESIGNATED_INITIALIZER;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment