aherlambang
aherlambang

Reputation: 14418

understanding self. in objective C

It's been 3 days since I've programmed in objective-C and I still don't quite understand the concept of self.

When should we use a self. in an implementation code? If I understand this correctly if I have defined it as a property then I should use self. But then the question is why? I've been reading many i-phone programming books but none doesn't seem to give me a strong and clear answer. Is self the same as this in other programming languages such as java?

Upvotes: 0

Views: 1118

Answers (5)

dreamlax
dreamlax

Reputation: 95335

self is roughly equivalent to this in other languages. Also, the dot-notation introduced in Objective-C 2.0 can mask what is really happening.

self.foo = 4;
NSInteger someInt = self.foo;

The above is the same as

[self setFoo:4];
NSInteger someInt = [self foo];

self is actually just a variable that is automatically passed to class and instance methods. This is what makes it possible to do:

self = [super init];
if (!self) return nil;

Upvotes: 2

willcodejavaforfood
willcodejavaforfood

Reputation: 44063

If you have defined a property and synthesised it using self.foo = bar will call a setter that has been generated for you. If you just do foo = bar you assign to your variable without going through the setter method. This means you won't take advantage of retain if the property was declared with retain or synchronisation.

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838216

self in Objective C is a pointer to the receiver of the current message, so it is a very similar concept to this in Java.

Upvotes: 3

element119
element119

Reputation: 7625

If you're used to programming in Java, think of self as Java's this.
For example, you'd use self in a class when you want to refer to something to do with that class- for example, in the class Car, self.wheels.

Upvotes: 1

Erick Robertson
Erick Robertson

Reputation: 33078

self in Objective-C is the same as this in Java.

In both cases, self and this are special variables inside an object which refers to the object itself. Use this when accessing properties or calling methods on the same object, or when calling an outside method to pass the object as a parameter.

If you think of self and this as the same thing, you will not have any problems. Of course, you can't actually use them interchangeably since each language recognizes only one of them.

Upvotes: 1

Related Questions