Initializer

init()

Implemented by subclasses to initialize a new object (the receiver) immediately after memory for it has been allocated. サブクラスによって実装されて、新しいオブジェクト(レシーバ)を、それのためのメモリが割り当てられた直後に初期化します。

Declaration 宣言

init()

Return Value 戻り値

An initialized object, or nil if an object could not be created for some reason that would not result in an exception.

Discussion 解説

An init() message is coupled with an alloc (or allocWithZone:) message in the same line of code:


SomeClass *object = [[SomeClass alloc] init];

An object isn’t ready to be used until it has been initialized. オブジェクトは、それが初期化されてしまうまで使われる準備ができていません。

In a custom implementation of this method, you must invoke super’s Initialization then initialize and return the new object. If the new object can’t be initialized, the method should return nil. For example, a hypothetical BuiltInCamera class might return nil from its init method if run on a device that has no camera.


- (instancetype)init {
    if (self = [super init]) {
        // Initialize self
    }
    return self;
}

In some cases, a custom implementation of the init() method might return a substitute object. You must therefore always use the object returned by init(), and not the one returned by alloc or allocWithZone:, in subsequent code.

The init() method defined in the NSObject class does no initialization; it simply returns self. In terms of nullability, callers can assume that the NSObject implementation of init() does not return nil.

See Also 参照

Creating, Copying, and Deallocating Objects オブジェクトの作成、複製、そして割り当て解除