objective c - Is it possible to write nonnull-annotation in init? -


now in objective-c there 2 new annotations: nonnull , nullable.
of them should use return type specification of init method?

- (instancetype)init {     if (self = [super init]) {         // ...     } } 

voice nullable:
there "if" check [super init] returns , there no guarantee never returns nil.

voice nonnull:
don't know real cases when init returns nil , never check it.

  • for arbitrary class, the docs -init state:

    return value: initialized object, or nil if object not created reason not result in exception.

a random class's init method can return nil. if you're returning result of [super init] subclass of class, there's possibility return nil. class should appropriately annotate init method nullable if returns result of nullable [super init].

each specific superclass object's init implementation must inspected determine if subclass's call [super init] can or will not return nil in turn.

this indicate method's annotation should nullable, unless have confirmed result of [super init] not nil.

  • for direct subclasses of nsobject, specifically:

    the init() method defined in nsobject class no initialization; returns self. in terms of nullability, callers can assume nsobject implementation of init() not return nil.

thus classes inheriting directly nsobject, -init can marked nonnull.

  • if your class returns nil

it's possible result of [super init] nonnull, class's implementation of init returns nil in response other condition.

- (instancetype)init {     if (self = [super init]) { // nonnull          if (somefailurecondition) {             return nil; // nullable         }      }      return self; } 

in case, implementation should of course annotated nullable.


Comments