Question

I was messing around with Objective-C and I stumbled upon something strange. The following code compiles and works the way I want it to.

self.scrollView.delegate = self.self.self.self.self;
// equivalent to         = self;

Why does this compile? Is it the case that self is a property of an object. If so, I have never seen self declared as a property. I thought self referred to the instance of the class you are creating.

Was it helpful?

Solution

Let me turn this around Why shoudn't it compile nor work as expected?

self is a property of NSObject. It always points to the object itself. Every object inheriting from NSObject has it.

As you say, self refers to the instance. Well, it is not only valid in the context of creating instances. It is always there. And it is very helpful.

[self myProperty] or self.myProperty refers explicitely (laugh more or less explicitely but it does) to the getter (or the setter) of the property myProperty while just typing myProperty within a method refers directly to the property without passing the getter.

Another example is someOjbect.delegate = self; or so.

So, as self alsways refers to an object, to the very object, it has a self property that refers to the very object which has a self property ...

BTW, classes are objects in Objective-C that inherit from Class. In the context of a class, i.e. in class methods, it refers to the class object of the very class. You can play the same game there. If you start off with an instance, then you can play the game with the class property.

self.class.class.class == [self class].self.class.self

should evaluate to YES. (Well, I never tried that myself. If you actually try it and find this wrong, then please let me know)

OTHER TIPS

self is a method in the NSObject protocol. It returns the object it is called on, it is rather pointless.

This is distinct from the local variable self, which within a method refers to the object the method was called on.

Both the method and the local variable apply to class objects as well as standard instances, so a class method has a self local variable and a class object a self method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top