Why is self allowed in static context in objective c

前端 未结 3 1553
清歌不尽
清歌不尽 2020-12-02 16:45

Why is using self allowed in static context in Objective-C?

I thought it was allowed and then I encountered memory errors that took me a week to find ou

3条回答
  •  没有蜡笔的小新
    2020-12-02 17:22

    self is only allowed within the context of an Objective-C method. By "static context" I assume you mean within a class method (that is, one whose signature starts with + rather than -.) Your assertion that "self is not an alias for calling other static methods" is incorrect.

    self is allowed in those cases so that you can:

    1. pass the class around as an object, since all Objective-C classes are themselves objects
    2. send messages to a class without specifying the class name, in case a method is overridden in a subclass ([Foo bar] will use Foo's implementation always; [self bar] will use whatever implementation is available in self.)

提交回复
热议问题