Dvole
Dvole

Reputation: 5795

Accessing member variable in objective c

What is the difference between the code:

[[self label] setText:@"Hello"];
[label setText:@"Hello"];

Is it correct that they are basically the same if I call them from inside the class? So if I call it from another class it will be:

[[someclass label] setText:@"Hello"];
someclass.label.text = @"Hello";

Is this correct? This self is disorientating me.

Upvotes: 0

Views: 96

Answers (4)

Joachim Isaksson
Joachim Isaksson

Reputation: 181077

The confusion stems from that @synthesize by default generates an iVar with the same name as the property.

The [[self label] setText:@"Hello"]; line will access the property label and call setText on that.

The [label setText:@"Hello"]; will access the iVar label and call setText on that.

The difference is that when you use the iVar, any settings you set on the property (atomic, copy, retain etc.) will not be respected.

It's usually better to just use the property if you don't have any particular reason not to. You can make this easier to remember by synthesizing the iVar with another name using;

@synthesize label = _label;

Upvotes: 0

CRDave
CRDave

Reputation: 9285

Yes both way are correct. in

someclass.label.text = @"Hello";

You are directly accessing the property

while in

[[someclass label] setText:@"Hello"];

You are using setter method to set value of text property which is created by objective C for you.

But I prefer set method more. but there is nothing wrong in using property.

Upvotes: 0

puneet kathuria
puneet kathuria

Reputation: 720

Self is only the way to show you that Label or anything you taking is belong to the current class. self will just tell you the entity belong to the same current class where you are declaring it or assigning some value to it.

And if you assigning that label to other class is a different thing.

Upvotes: 0

Carl Veazey
Carl Veazey

Reputation: 18363

self is a pointer to the object that's had the method called on it.

[label setText:] would presumably access the instance variable directly. The other ways all go through the accessor method.

Upvotes: 1

Related Questions