-2

I'm learning Objective-C and i have a confusion about self ,so here is the code : the interface :

@interface Person : NSObject
{
float HeightInMeters;
int WeightInKilos;
}
@property float HeightInMeters;
@property int WeightInKilos;
- (float) BodyIndex;

@end

the implementation without self:

@implementation Person
@synthesize HeightInMeters,WeightInKilos;
-(float)BodyIndex
{
    float h=HeightInMeters;
    float w=WeightInKilos;
    return w/(h*h);
}
@end

the implementation using self:

@implementation Person
@synthesize HeightInMeters,WeightInKilos;
-(float)BodyIndex
{
    float h=[self  HeightInMeters];
    float w=[self  WeightInKilos];
    return w/(h*h);
}
@end

so here is the question : with or without self both code are working fine , so what is the purpose of using self ? thanks

satyres
  • 377
  • 1
  • 5
  • 17

4 Answers4

1

self allows you to be more explicit about where the information is coming from.

For example, you could have a method like this:

- (BOOL)isEqual:(id)other {
  return [self class] == [other class] && [self info] == [other info];
}

Also, depending on the memory semantics of your property, if you do something like self.info = someInfoObject the synthesized property method will manage the retain and release calls for you.

Having the self identifier makes it clearer. If you're familiar with Java or C++. self is somewhat akin to this.

Ben S
  • 68,394
  • 30
  • 171
  • 212
  • so , this means that there is no real purpose to use Self just to be more explicit right ? – satyres Sep 23 '13 at 19:27
  • @satyres No, that's not a right conclusion to reach from this answer: there's a very real purpose behind using `self` in your example - it makes a difference between a variable access and a method call. – Sergey Kalinichenko Sep 24 '13 at 20:45
0

you can remove @synthesize on your code. if you remove this, you can access to your @property with self or _ :

@property float heightInMeters;

_heightInMeters or self.heightInMeters

Here a link to explain how to use correctly self and what is it ;)

Jordan Montel
  • 8,227
  • 2
  • 35
  • 40
0

When you use [self HeightInMeters] you are accessing the property named HeightInMeters. When you just use HeightInMeters you are accessing the backing field for that property because of how you wrote the @synthesize.

See more in the Apple docs for properties.

DocMax
  • 12,094
  • 7
  • 44
  • 44
0

Going through accessor methods (which is what's really different here) is a fundamentally different operation from accessing an instance variable. If you don't call the method, the code in that method won't run, so none of its side effects will happen (notifying via KVO, retaining/releasing under non-ARC, doing lazy initialization, whatever you write in the method yourself).

Catfish_Man
  • 41,261
  • 11
  • 67
  • 84