Why is self allowed in static context in objective c
Why is using self
allowed in static co开发者_开发知识库ntext in Objective-C?
I thought it was allowed and then I encountered memory errors that took me a week to find out that self
is not an alias for calling other static methods from the class instead of typing the class name.
Xcode and its compiler seems very smart at finding common pitfalls, why isn't it even generating a warning about something like that?
- There is no such thing as a "static context" in Objective-C. What we have instead are "class methods". They definitely are not "static" methods.
- Class methods (ones prefixed with a
+
) are really just instance methods on a particularClass
object. (did your mind just explode?) And since you have aself
variable accessible in an instance method, you naturally have aself
variable accessible in the class method as well. - In a class method,
self
points to the class itself. - Just as you can do
[self performAction]
inside an instance method to invoke methods on this particular instance, you can do[self performClassAction]
inside a class method to invoke methods on this particular class. - All
Class
objects are subclasses ofNSObject
. So you can use anyNSObject
instance method on anyClass
object. (did your mind just explode again?)
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:
- pass the class around as an object, since all Objective-C classes are themselves objects
- send messages to a class without specifying the class name, in case a method is overridden in a subclass (
[Foo bar]
will useFoo
's implementation always;[self bar]
will use whatever implementation is available inself
.)
It's allowed because self
does refer to the class object when used in class methods. Is that what you mean by "static context?" If so, what memory errors were you having that suggested otherwise?
精彩评论