tags:

views:

54

answers:

2

First time poster so please be gentle.

How do you reference a method in the current object in Objective-C? Is there something like in Java, the this keyword?

Here is some fake code to clarify:

@implementation FooBard
- (void) foo {
   i = 1
   m = [this bar: i];
}

- (int) bar: int j {
   k = j - 1;
   return (k);
}
@end

In Java I would just do this.bar() and be done with it.

Thanks for the time.

Bill

+2  A: 
m = [self bar:i];
Abizern
that works. Thank You.
bkoch
Short and sweet as it was ;-)
Abizern
+1  A: 

All Objective-C methods get an implicit parameter called self that is a stack variable of type id that points to the current instance. In fact, any C function can be used as an Objective-C method if its first two parameters are type id and SEL (see below).

self is not a reserved keyword in Objective-C like this in Java. You can, for example reassign self within the method. This is a standard pattern in init methods:

-(id)init {
  if( (self = [super init]) ) {
    // do initialization here
  }

  return self;
}

but reassigning self is rarely used in any other context.

You can use self like any other variable of type id: [self bar:i] in the example you provide.

For completeness, all Objective-C methods also get an implicity parameter named _cmd as well which is the selector (type SEL) of the method being called. See the Objetive-C Runtime Reference for more info.

Barry Wark
_cmd is a good one to use in NSLog statements. such as NSLog(@"%s: my message and object: %@", _cmd, myObject);
Abizern