tags:

views:

60

answers:

5

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?

+1  A: 

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.

Erick Robertson
A: 

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.

Chromium
+2  A: 

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.

Mark Byers
+1  A: 

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.

willcodejavaforfood
+2  A: 

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;
dreamlax