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 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?
self is a special variable in Objective-C, inside an instance method this variable refers to the receiver(object) of the message that invoked the method, while in a class method self will indicate which class is calling.
But static contexts(methods and blocks) doesn't have any instance they belong to the class. In a simple sense, to use “this” the method should be invoked by an object, which is not always necessary with static methods. Therefore, you cannot use this keyword from a static method.
From Wikipedia: Static methods neither require an instance of the class nor can they implicitly access the data (or this, self, Me, etc.) of such an instance. This describes exactly what Objective-C's class methods are not.
Static properties are accessed using the Scope Resolution Operator ( :: ) and cannot be accessed through the object operator ( -> ). It's possible to reference the class using a variable. The variable's value cannot be a keyword (e.g. self , parent and static ).
+
) 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?)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
.)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With