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
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:
[Foo bar]
will use Foo
's implementation always; [self bar]
will use whatever implementation is available in self
.)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?
+
) are really just instance methods on a particular Class
object. (did your mind just explode?) And since you have a self
variable accessible in an instance method, you naturally have a self
variable accessible in the class method as well.self
points to the class itself.[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.Class
objects are subclasses of NSObject
. So you can use any NSObject
instance method on any Class
object. (did your mind just explode again?)