self.variableName vs. _variableName vs. @sysnthesize variableName [duplicate]
Asked Answered
R

2

8

Possible Duplicate:
How does an underscore in front of a variable in a cocoa objective-c class work?


Note: For the folks digging around trying to understand this, I figured-out the source of my confusion. In the .h, I had:

...
@interface myClass : parentClass {
className *variableName:
}

@property (strong, nonatomic) className  *variableName;
...

This leads to self.variableName and _variableName being two distinct variables in the .m. What I needed was:

...
@interface myClass : parentClass {
className *_variableName:
}

@property (strong, nonatomic) className  *variableName;
...

Then, in the class' .m, self.variableName and _variableName are equivalent


In brand-new, Xcode 4.5+, with ARC, targeting iOS 5.0+ project, is there a distinct advantage (runtime efficiency, speed, etc.) to using _variableName over self.variableName vs. the old-style @synthesize variableName?

My understanding is that Xcode 4.5+ will create a default accessor _variableName that is equivalent to self.variableName and the only reasons not to use @synthesize variableName is to avoid confusion between iVars and passed-in variables, correct?

To me, just using self.variableName to access an iVar seems the most straightforward and clear as to which variable you're looking for. Other than typing _ vs. self., is there an advantage to using _variableName?

Roomful answered 1/1, 2013 at 17:46 Comment(3)
And here's another 16: https://mcmap.net/q/663237/-underscore-prefix-on-property-name-duplicate https://mcmap.net/q/619256/-synthesized-property-and-variable-with-underscore-prefix-what-does-this-mean-duplicate https://mcmap.net/q/1322740/-why-do-you-use-an-underscore-for-an-instance-variable-but-not-its-corresponding-property-duplicate https://mcmap.net/q/778841/-why-put-underscore-quot-_-quot-before-variable-names-in-objective-c-duplicate https://mcmap.net/q/1322741/-what-does-an-underscore-signify-in-the-name-of-a-member-variable-in-objective-c-duplicate https://mcmap.net/q/467480/-when-do-you-make-an-underscore-in-front-of-an-instance-variable-duplicate https://mcmap.net/q/260232/-prefixing-property-names-with-an-underscore-in-objective-c-duplicate https://mcmap.net/q/1322742/-objective-c-synthesize-property-duplicate https://mcmap.net/q/1322743/-instance-variables-with-underscore-in-objective-c-2-0-and-renaming-with-synthetize-leads-to-optimization-warnings-by-the-39-analyze-39-tool-of-xcode-4-duplicate https://mcmap.net/q/1264926/-objective-c-what-is-the-advantage-of-doing-synthesize-myvar-_myvar-if-any-duplicate https://mcmap.net/q/260232/-prefixing-property-names-with-an-underscore-in-objective-c-duplicate https://mcmap.net/q/1322744/-objective-c-synthesize-foobar-vs-synthesize-foobar-_foobar-duplicate stackoverflow.com/q/9696359 https://mcmap.net/q/1322745/-property-declaration-help-duplicate https://mcmap.net/q/174750/-why-rename-synthesized-properties-in-ios-with-leading-underscores-duplicate https://mcmap.net/q/571862/-iphone-ivar-naming-convention-duplicateYanina
My bad. I din't think of searching for 'underscore' spelled-out. That said, spot-checking a few of the potential dups, I didn't see any/newbie-proof mention of the potential issues with key-value observation, bindings and thread-safe access (atomic) if _variableName is used vs. self.variableName. One (4088801) did mention a potential issue if the object referred to in _variableName is shared and recommended using self.variableName instead.Roomful
If you see a specific issue that's overlooked in one of the many instances of the overall question, you should certainly feel free to ask about it in detail. There's little value, however, in having that information just happen to be buried in yet another copy.Yanina
F
17

My understanding is that Xcode 4.5+ will create a default accessor "_variableName" that is equivalent to self.variableName and the only reasons not to use "@synthesize variableName" is to avoid confusion between iVars and passed-in variables, correct?

In this case, _variableName isn't the accessor, it's an ivar that is automatically generated by the compiler and used in the automatically @synthesized setters and getters. Generally, it is considered best to use accessors whenever possible (i.e. self.variableName) so that things like key-value observation and bindings work for that property.

When you access an ivar directly, it is accessed via direct memory access, the same way you would access data in a struct. It simply takes the pointer for the object that owns the ivar, offsets the memory address and attempts to read or write to the memory at that location. Using dot notation (self.variableName) calls the accessor methods to set or get that property and can do a number of different things along the way, such as:

1) Locking: If the property is going to be used in multiple threads and is an atomic property, the runtime will automatically do some locking to make sure that the property is not accessed at the same time from multiple threads. If your object is not meant to be used on multiple threads, you can give the nonatomic hint in your property declaration so that the synthesized accessors skip the locking.

2) Key-Value Notifications: The default setters for properties call -willChangeValueForKey: and -didChangeValueForKey:, which sends out notifications when the property is changed. This is necessary for anything to update properly if bindings are used, and for any other key-value observation.

3) Custom accessor behavior: If you end up writing your own setters and getters, any custom stuff that you implement within those.

Technically, accessing the ivar directly is faster than using accessors, but there are very few situations in which it will make a significant performance difference, and would probably be a case of premature optimization. Even if you don't feel like you would be using the benefits listed above right away, it's probably better to use the accessors anyway so that if you decide later on you need some of that functionality, you don't have to change every instance of accessing that variable (and possibly be creating unexpected new bugs in the process).

In addition, if you are accessing ivars directly and end up refactoring your class into categories or subclasses, it gets messy because you usually have to declare the ivar as a @protected variable. You wouldn't have to do this if you are using the accessors.

Generally, I try to only access the ivars directly in init, dealloc, and the property's accessor. A lot of engineers go by this rule of thumb because sometimes the custom stuff that happens in accessors can cause unexpected behavior while the object is init'ing or dealloc'ing. For example, if anything in the accessors causes something to retain or release your object or even form a zeroing weak reference to it, it will cause a crash if used in dealloc.

Fortyniner answered 1/1, 2013 at 18:33 Comment(0)
S
5

In the latest Xcode @synthesize is optional. By default, omitting @synthesize is the same as writing

@synthesize someName = _someName;

The only reason to use @synthesize is to rename the instance variable created to store the value of the property, for example

@synthesize someName = someSpecialName;

When you use self.variableName to access a variable, you go through a property, which is a short method that accesses the instance variable for you. Although the method dispatch is very fast, it may perform additional services for you, such as synchronizing the access to the variable (this is the case when you specify atomic or do not specify nonatomic in the property declaration). In cases like that, the access through self.variableName will be somewhat slower. If done in a tight loop, this could potentially make a difference. That is why you sometimes want to access the underlying instance variable directly by using _variableName.

Situated answered 1/1, 2013 at 17:56 Comment(3)
Just to be pedantic, based on your reply and @eyebrowsoffire, _variableName, might be faster, but self.variableName is safer?Roomful
@RayatERISCorp "Safer" is underdefined in this context, but if your intention was to use a property in a synchronized way (i.e. it's atomic) then the answer is yes, it is safer. In fact, the other way (i.e. going for _variableName directly) simply does not work without additional locking.Situated
Gotcha. By "safer" I mean "less likely to trigger some unexpected bug in my code that will leave me debugging for much longer than I should have been because using _variableName doesn't automagically kick-off some action that self.variableName does."Roomful

© 2022 - 2024 — McMap. All rights reserved.