Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

objective C underscore property vs self

Tags:

objective-c

I'm was playing around with the standard sample split view that gets created when you select a split view application in Xcode, and after adding a few fields i needed to add a few fields to display them in the detail view.

and something interesting happend in the original sample, the master view sets a "detailItem" property in the detail view and the detail view displays it.

- (void)setDetailItem:(id) newDetailItem
{
if (_detailItem != newDetailItem) {
    _detailItem = newDetailItem;

    // Update the view.
    [self configureView];
}

i understand what that does and all, so while i was playing around with it. i thought it would be the same if instead of _detailItem i used self.detailItem, since it's a property of the class.

however, when i used

self.detailItem != newDetailItem

i actually got stuck in a loop where this method is constantly called and i cant do anything else in the simulator.

my question is, whats the actual difference between the underscore variables(ivar?) and the properties? i read some posts here it seems to be just some objective C convention, but it actually made some difference.

like image 523
Pita Avatar asked Dec 08 '12 10:12

Pita


People also ask

What does underscore mean in Objective-C?

The point of the underscore in front of the name is to reinforce the point that you're not supposed to be using it directly all over your code—only within the accessor methods.

What is self in Objective-C?

self is a special variable in Objective-C, inside an instance method this variable refers to the receiver(object) of the message that invoked the method, while in a class method self will indicate which class is calling.

Why do some variables have underscore in front?

A single leading underscore in front of a variable, a function, or a method name means that these objects are used internally. This is more of a syntax hint to the programmer and is not enforced by the Python interpreter which means that these objects can still be accessed in one way on another from another script.


1 Answers

_property means you are directly accessing the property.

self.property means you are using accessors.

In your case, in the setter method you are calling it, creating a recursive call.

like image 62
Anoop Vaidya Avatar answered Oct 14 '22 07:10

Anoop Vaidya