Naming convention of instance variables when synthesizing properties - ios

When synthesizing properties in Objective-C, it's recommended that you dont simply write:
#synthesize window;
but rather
#synthesize window = _window;
The reasoning is that you don't want your instance variable named the same as your getter method or "bad things can happen".
I've always used #synthesize var1, var2, etc in my apps without "bad things" happening. What sort of bad things could happen?

Bad things used to happen, particularly in the pre-ARC days when people would assign objects to the storage iVar instead of the property. If this was done by accident, then the memory management implied by the synthesized setter wouldn't be applied, leading to leaks, or premature releases.
I use to do it the simple way, but now I use prefixes. I don't declare my iVar themselves anymore, I let the modern runtime take care of that for me. I use prefixes so that I don't accidentally use an iVar like a local variable.
Also - I tend to refer to my properties as self.iVar almost everywhere in my classes. This is so that I can use lazy loaded properties when I want to without worrying about which ones are and are not lazily loaded.

The biggest reason for using the leading underscore in instance variables (like _myProperty) is that when people read the code with the leading underscore, they know that you are using an instance variable, not a local variable, a global variable, or forgot to write "self." like self.myProperty, and that you did this intentionally.
Before ARC, _myProperty wouldn't do any reference counting, while self.myProperty would (for "retain" / "strong" properties). With ARC when you are using "copy" properties, _myProperty does reference counting but still does no copying, so there is still some difference. The most important difference is that _myProperty won't trigger any observers.

Related

How to know which attributes to use with different properties? [duplicate]

Can someone explain to me in detail when I must use each attribute: nonatomic, copy, strong, weak, and so on, for a declared property, and explain what each does? Some sort of example would be great also. I am using ARC.
Nonatomic
Nonatomic will not generate threadsafe routines thru #synthesize accessors. atomic will generate threadsafe accessors so atomic variables are threadsafe (can be accessed from multiple threads without botching of data)
Copy
copy is required when the object is mutable. Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy.
Assign
Assign is somewhat the opposite to copy. When calling the getter of an assign property, it returns a reference to the actual data. Typically you use this attribute when you have a property of primitive type (float, int, BOOL...)
Retain
retain is required when the attribute is a pointer to a reference counted object that was allocated on the heap. Allocation should look something like:
NSObject* obj = [[NSObject alloc] init]; // ref counted var
The setter generated by #synthesize will add a reference count to the object when it is copied so the underlying object is not autodestroyed if the original copy goes out of scope.
You will need to release the object when you are finished with it. #propertys using retain will increase the reference count and occupy memory in the autorelease pool.
Strong
strong is a replacement for the retain attribute, as part of Objective-C Automated Reference Counting (ARC). In non-ARC code it's just a synonym for retain.
This is a good website to learn about strong and weak for iOS 5.
http://www.raywenderlich.com/5677/beginning-arc-in-ios-5-part-1
Weak
weak is similar to strong except that it won't increase the reference count by 1. It does not become an owner of that object but just holds a reference to it. If the object's reference count drops to 0, even though you may still be pointing to it here, it will be deallocated from memory.
The above link contain both Good information regarding Weak and Strong.
nonatomic property means #synthesized methods are not going to be generated threadsafe -- but this is much faster than the atomic property since extra checks are eliminated.
strong is used with ARC and it basically helps you , by not having to worry about the retain count of an object. ARC automatically releases it for you when you are done with it.Using the keyword strong means that you own the object.
weak ownership means that you don't own it and it just keeps track of the object till the object it was assigned to stays , as soon as the second object is released it loses is value. For eg. obj.a=objectB; is used and a has weak property , than its value will only be valid till objectB remains in memory.
copy property is very well explained here
strong,weak,retain,copy,assign are mutually exclusive so you can't use them on one single object... read the "Declared Properties " section
hoping this helps you out a bit...
This link has the break down
http://clang.llvm.org/docs/AutomaticReferenceCounting.html#ownership.spelling.property
assign implies __unsafe_unretained ownership.
copy implies __strong ownership, as well as the usual behavior of copy
semantics on the setter.
retain implies __strong ownership.
strong implies __strong ownership.
unsafe_unretained implies __unsafe_unretained ownership.
weak implies __weak ownership.
Great answers!
One thing that I would like to clarify deeper is nonatomic/atomic.
The user should understand that this property - "atomicity" spreads only on the attribute's reference and not on it's contents.
I.e. atomic will guarantee the user atomicity for reading/setting the pointer and only the pointer to the attribute.
For example:
#interface MyClass: NSObject
#property (atomic, strong) NSDictionary *dict;
...
In this case it is guaranteed that the pointer to the dict will be read/set in the atomic manner by different threads.
BUT the dict itself (the dictionary dict pointing to) is still thread unsafe, i.e. all read/add operations to the dictionary are still thread unsafe.
If you need thread safe collection you either have bad architecture (more often) OR real requirement (more rare).
If it is "real requirement" - you should either find good&tested thread safe collection component OR be prepared for trials and tribulations writing your own one.
It latter case look at "lock-free", "wait-free" paradigms. Looks like rocket-science at a first glance, but could help you achieving fantastic performance in comparison to "usual locking".

The best route to declare a BOOL as iVar or Property

I have read a few questions on the differences between iVars and Properties like these: Why would you use an ivar?
ios interface iVar vs Property
What I would like to know is... If I am creating a BOOL that needs to be accessed in multiple methods in a UIViewController (for example) what is the best way to create these?
At present I create proprties. This works fine and as expected. But as I read/learn more it appears that creating an iVar would be better for performance.
Like:
#interface ViewController : UIViewController{
BOOL myBool;
}
Would this be better for performance, and can multiple methods access this iVar if I set the value to YES in one, can I check the value in the other - as I can with property approach?
can multiple methods access this iVar if I set the value to YES in one, can I check the value in the other
Of course you can, even if you set the value to NO. It is an instance variable and thus shared between all methods of one instance.
Would this be better for performance
No, unless you access the property very, very often, like 2^20 times per frame. Have a look at this Big Nerd Ranch post about iVar vs property performance. Usually the performance gain is not worth the loss in clarity.
The "better performance" is something that would be very rare to affect an app. Write code for clarity, then if there are performance issues profile and fix the code that is actually causing the problem.
For your purpose an ivar would be equivalent to using a property. Performance-wise the ivar is slightly better because you access it directly, whereas with a property you invoke a method (getter or setter) that was generated by the compiler in the background.
I wouldn't worry about performance, though. Typically the difference will be negligible. Unless you have some really special need, I would always use properties because it usually results in clearer code. It's also a good habit to have getter and setter methods - even if they are generated by the compiler for you - because they encapsulate the data of your class.
I usually go with this:
#interface MyVC : UIViewController
#property (nonatomic, getter=isDoingSomething) BOOL doingSomething;
#end
I also explicitly name the getter in the property declaration which gives you access to the property in a way that is easy to read. (Setting the property is done by sending setDoingSomething: and the getter is [theVC isDoingSomething])
Nonatomic properties are recommended on iOS. In regards to what I had backwards before, the default atomic behavior adds locks to the synthesized code, and is not recommended for performance reasons. Any issues with threads would have to be handled in your own setters (which you would have to do anyway when using an ivar). Personally I haven't ran into any issues with this.
I won't repeat other answers about performance but besides pointing out the fact that tapping a button sends way more messages than accessing a property, so the performance penalty is trivial.

Properties and their backing ivars

Hi imagine I have properties in the .h file:
#property (nonatomic) NSString * myText;
#property (nonatomic) SomeClass * someObj;
Now, in the class implementation.
Say, I didn't forget to use synthesize, and I called:
#synthesize myText, someObj;
Now say in code I forget to put self before the property name (and directly refer to the ivar):
myText = #"Hello";
someObj = [[SomeClass alloc] init];
My question is: is this a problem? What problems can it result in? Or it is no big deal?
ps. Say I am using ARC.
My question is: is this a problem?
This is called "direct ivar access". In some cases, it's not a problem, but a necessity. Initializers, dealloc, and accessors (setters/getters) are where you should be accessing self's ivars directly. In almost every other case, you would favor the accessor.
Directly accessing ivars of instances other than self should be avoided. Easy problem here is that you may read or write at an invalid address (undefined behavior), much like a C struct. When a messaged object is nil, the implementation of that message is not executed.
What problems can it result in?
Biggest two:
You won't get KVO notifications for these changes
And you are typically bypassing the implementation which provides the correct semantics (that can be justified). Semantics in this case may equate to memory management, copying, synchronization, or other consequences of a change of state. If, say, a setter is overridden, then you are bypassing any subclass override of that setter, which may leave the object in an inconsistent state.
See also: Why would you use an ivar?
For clarity, I recommend always using
self.propertyname
as opposed to
propertyname
as this removed any confusion between what variable belong to the class or have been declared locally above in the method.
To enforce this, try to avoid using #synthesize at all, which is only needed if you provide both custom getter and setter (but not one or the other)
The compiler automatically allows you to use _propertyname in the getter/setter (which is necessary to prevent recursive calls of the function)
You should not access the underlying instance variables by accident, only if you plan to do so.
Unexpected side effects may be that KVO doesn't work, overriding accessor methods are not called and the copyand atomic attributes have no effect.
You don't need to use #synthesize since Xcode 4.4, if you use default synthesis the compiler does an equivalent of
#synthesize myText = _myText;
so that
_myText = #"Hello";
self->_myText = #"Hello";
are equivalent and myText = #"Hello"; results in an "undefined identifier" compiler error.
If you use just #synthesize myText the compiler does (for backward compatibility reasons):
#synthesize myText = myText;
which is error prone.
Note that there are valid reasons to use the underlying instance variables instead of the accessor - but it's bad style to do this by accident.
For 30 years now, the recommended practice has been:
use getter/setter methods or the new . operator to read and write ivars.
only access ivars directly when you must.
pick ivar names to prevent accidentally using them, unless the ivar is one that will always be accessed directly (that is why the default behaviour and convention is to prefix ivars with an underscore).
You need to access ivars directly in a few situations:
Manual memory management requires it. You won't need this if ARC is enabled.
If you are going to read the variable variable millions of times in quick succession, and you can't assign it to a temporary variable for some reason.
When you're working with low level C API, it probably needs a pointer to the ivar, Apples libxml2 sample code accesses ivars directly for example.
When you are writing the getter or setter method yourself, instead of using the default #synthesize implementation. I personally do this all the time.
Aside from these situations (and a few others), do not access ivars directly. And prefix all ivars with an underscore, to make sure you don't accidentally access them and to prevent them appearing in xcode's autocomplete/intellisense while you code.
The two main reasons for the convention are:
Getter/setter methods and properties can be kept around when the underlaying memory structure of your class changes. If you rename an ivar, all code that reads the ivar will break, so best to have zero code or almost no code that accesses ivars directly.
Subclasses can override getters and setters. They cannot override ivars. Some people think subclasses shouldn't be allowed to override getters and setters - these people are wrong. Being able to override things is the entire point of creating a subclass.
Fundamental features like KVC and KVO can fall apart if you access ivars directly.
Of course, you can do whatever you want. But the convention has been around for decades now and it works. There is no reason not to follow it.
Contrary to what other answers seem to agree upon, I would recommend to always use direct ivar access unless you are very clear about what you are doing.
My reasoning is simple:
With ARC, it's not even more complicated to use direct property access, just assign a
value to the ivar and ARC takes care of the memory management.
(And this is my main point:) Property accessors may have side-effects.
This is not only true for property accessors you write, but may also be true for
subclasses of the class you are implementing.
Now these accessors defined in subclasses may very well rely on state that the subclass
sets up in it's initializer, which has not executed at this point, so you calling those
accessors might lead to anything from undefined state of your object to your application
throwing exceptions and crashing.
Now, not every class may be designed to be subclassed, but I think it's better to just use one style everywhere instead of being inconsistent depending on the class you are currently writing.
On a side note: I would also recommend to prefix the name of every ivar with an _, as the compiler will do automatically for your properties when you don't #synthesize them.

Why are __block variables not retained (In non-ARC environments)?

I was reading through the documentation on __block variables, and thinking about the cases where I use __block. To me, it seems like I need it in two cases:
To mark a variable as read-write when used within a block
To avoid retain cycles when referencing self within a block
On the surface it doesn't seem like these two things are related. I consider the fact that __block variables not being retained as more of a trick I need to remember for the specific use case of avoiding retain cycles.
I'm wondering, is there a more important, architectural reason why they must not be retained? I would think some other keyword to indicate this might be more clear, as to not mix up the two features listed above.
update -
I should mention this is code that does not use ARC. I now see that __block variables are in fact retained in ARC.
__block variables are not retained if you use Manual Reference Counting. The reason can be found here: http://www.mikeash.com/pyblog/friday-qa-2009-08-14-practical-blocks.html:
A simple workaround to this lies in the fact that __block variables
are not retained. This is because such variables are mutable, and
automatic memory management of them would require each mutation to
generate memory management code behind the scenes. This was seen as
too intrusive and difficult to get right, especially since the same
block may be executing from multiple threads simultaneously.
and also here: http://lists.apple.com/archives/objc-language/2009/Dec/msg00100.html
There is no way to properly and efficiently manage the retain counts
upon re-assignment of the value within the variable.
(I could not find an "official" reference in the Apple documentation.)
As documented in the "Transitioning to ARC Release Notes", this behavior changed with ARC:
In manual reference counting mode, __block id x; has the effect of not
retaining x. In ARC mode, __block id x; defaults to retaining x (just
like all other values). To get the manual reference counting mode
behavior under ARC, you could use __unsafe_unretained __block id x;.
As the name __unsafe_unretained implies, however, having a
non-retained variable is dangerous (because it can dangle) and is
therefore discouraged. Two better options are to either use __weak (if
you don’t need to support iOS 4 or OS X v10.6), or set the __block
value to nil to break the retain cycle.

Do I need ARC keywords for properties that I don't synthesize?

I have a property that I do not synthesize, instead I create a getter and setter myself. Therefore, the ARC keywords (strong or weak) have no meaning, I assume, so I eliminate them. This works fine on Xcode 4.3, but when my coworker opens them on XCode 4.2 the compiler complains that there is no strong/weak keyword, so I instructed him to meaninglessly enter the keyword back in again. Which is correct (with or without keywords)?
To be clear: I have a property like this #property (nonatomic) NSString *foo and in the .m file I implement -(NSString *)foo and -(void)setFoo:(NSString *)foo and do NOT include #synthesize foo. Another relevant detail is that there is no corresponding iVar, instead the properties interact with a Core Data object. This will not compile in XCode 4.2 unless I add strong or weak to the keywords.
EDIT I thought of one more relevant thing, one of these properties is on a Protocol, I don't know if that makes a difference.
The declared attributes that you are referencing are optional. To quote the documentation:
Property Declaration and Implementation
The #property directive declares a property. An optional parenthesized
set of attributes provides additional details about the storage
semantics and other behaviors of the property - see “Property Declaration Attributes” for possible values.
Property Declaration Attributes
You can decorate a property with
attributes by using the form #property(attribute [, attribute2, ...]).
Like methods, properties are scoped to their enclosing interface
declaration. For property declarations that use a comma-delimited list
of variable names, the property attributes apply to all of the named
properties.
If you use the #synthesize directive to tell the compiler to create
the accessor methods (see “Property Implementation Directives”), the
code it generates matches the specification given by the keywords. If
you implement the accessor methods yourself, you should ensure that it
matches the specification (for example, if you specify copy you must
make sure that you do copy the input value in the setter method).
If you then use #dynamic instead of #synthesize it is telling the compiler that you will be writing your own methods and prevents it from complaining when it doesn't find suitable methods.
More information can be found here.
borrrden,
First, why do you care to elide your memory policy in your property statement? It announces to consumers of your class what the policy is. Don't you want them to know?
Second, the #synthesize is not a nop. It is the mechanism by which the language support KVO. While you may not be using that now, why would you preclude this use for the future.
Frankly, by not using a full description in #property nor using #synthesize, you are, IMO, engaging in premature optimization. Your current design doesn't save you message dispatches and forces you to manage, if necessary, the creation and typing of ivars. And you are losing features of the language.
Unless you have a good reason to get outside the bounds of the preferred Obj-C v2+ patterns, and you haven't listed those, then I would return to using the standard pattern. Then your problem just goes away.
Andrew

Resources