I passed the Objective-C test on it.mail.ru and I want more information.

Question: “What will happen?” (_InstanceVariable is an object, ivar of the current object)

^{ NSLog(@"%@ ", _instanceVariable); } 

Variants of answers:

  • Nothing
  • self
  • _instanceVariable
  • both that, and that

I replied: "nothing", and this was noted as an incorrect answer. I see the error in my logic, _instanceVariable will be captured by the block. But will self-banning be?

I would also appreciate a clear description of the cases in which ivar is used. All I found in the documentation is:

I did not become clearer.

    2 answers 2

    _instanceVariable for the compiler is similar to self->_instanceVariable , thus, self will also be found.

    Instance variable is not recommended to use directly, it is described in the document "Adopting Modern Objective-C" on the Apple Developer website. Instead, it is proposed to use property with the necessary attributes, for which the compiler itself will create the corresponding ivars and will generate getters and setters.

    I know only the following cases when I should refer directly to ivars instead of property:

    1. In initializers, since getters and setters can have side effects depending on still non-initialized properties.
    2. In the implementation of the NSCopying protocol for the direct transfer of ivar values ​​between the original object and its copy (the reason is the same as in the last paragraph)
    3. In the implementation of their own getters and setters. I think, obviously, why.

      Only self will be disabled. Dmitry writes "also", implying that both this and that will be confused, but this is not the correct conclusion from the correct message that this is a variable for the compiler via an arrow: self->_instanceVariable .