user1487403
user1487403

Reputation:

self in objective C

-(void)setFaceView:(FaceView *)faceView  
{
_faceView= faceView;
self.faceView.dataSource = self;
}

I just started learning IOS programming with famous Stanford lectures on iTunes. I am currently at lecture 6 and I start to have difficulty catching up with the class.

It is a really basic thing, but I really don't understand how 'self' works. Can anyone teach me what 'self's in this code are doing?

Upvotes: 0

Views: 226

Answers (2)

The Lazy Coder
The Lazy Coder

Reputation: 11838

self is the object itself. when you alloc an object. it sets aside enough memory to hold all the variables that class will use.

when you init the object however you attach that memory to self. self is essentially a "variable" (and i use the term loosely) that gives you access to all the functions of the object you are within.

if you have an object with the following method

+(BOOL) isThisWorking{ return YES;}

you would have to call the method on the class. Self is not involved.

however if you have a method

-(BOOL) isThisWorking{ return YES; }

then you would have a method attached to an instance of a class.

calling the first one would require you to call it on the class object itself.

[MyObject isThisWorking];

calling the second one would require you to call it on an instance.

MyObject *testObject = [[MyObject alloc] init];
[testObject isThisWorking];

when you are in a method within test object you will not have the 'testObject' to call methods on.

self fills that void.

if you come from another programming language you will be familiar with other constructs that do the same thing.

for instance in .net the object is "this"

and in old school vb if i remember correctly the object is "Me"

Upvotes: 1

ehope
ehope

Reputation: 516

self is an implicit parameter in objective-c of instance methods that refers to the object performing the method - see here: Messages to Self and Super

In this case, self.faceView is a call to the property accessor for faceView that is bound to the instance that runs this method, while the assignment _faceView= faceView; is assigning the input parameter faceView to the iVar _faceView. self.faceView.dataSource = self; assigns the object performing this method to the dataSource property of the object's faceView property.

Upvotes: 2

Related Questions