Objective-C supports it, although in that case the keyword is self
instead of this
. In Objective-C, self
is passed as a hidden parameter to all class methods (as is another hidden parameter named _cmd
, which is a pointer to a C string containing the name of the message being sent, but that is irrelevant for this discussion). So, a method declared like this:
@implementation MyClass
- (void) doSomething:(int)arg1 withArg2:(float)arg2
{
...
}
@end
Gets turned into something like this:
// actual function name will be something else, this is just an example
void MyClass_doSomething(id self, const char *_cmd, int arg1, float arg2)
{
...
}
self
can be reassigned to, but since it's really just a local variable, assigning to it will only have effect during the function call. Supposing that doSomething:withArg2:
assigned to self
, and consider the following code:
MyClass *inst = [[MyClass alloc] init];
[inst doSomething:3 withArg2:4.0f];
After the call to doSomething:withArg2:
, the value of inst
remains unchanged. Assigning to self
there only affects the local variable named self
, not the actual object.
So how is this useful? Well, when an object initialization method fails for some reason, it is customary to return nil
instead of the object, and to free the object to prevent memory leaks. When you have inheritance, the subclass needs to make sure the parent's init
method succeeded before it can proceed. The following is a common idiom:
- (id) init
{
if((self = [super init]))
{
// initialize subclass
}
return self;
}
If the parent class' init
routine fails, it returns nil
, and the local variable self
is assigned nil
. The extra parentheses in the if
statement are to suppress a compiler warning about using =
instead of ==
in the if
statement -- we really want =
here. Finally, self
is returned, which will be nil
if we failed, or the object if we succeeded.