Alex Rivera | Logout

Why is self allowed in static context in objective c

Asked 2011-06-12T23:37:50.133
43

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?

Edit
Report

1 Answer

8

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.)
answered 2011-06-12T23:41:16.140

Your Answer