Using #synthesize in ios Application - ios

I was watching the wonderful Paul Haggerty in the iTunesU courses for iOS development (cause who doesn't need to refresh on the basics?) and he said something that I wasn't aware of:
"We will never access underbar ( the _ symbol) variables"
He then went on to talk about how when you use #property to declare your variables,#synthesize variable = _variable is code that's generated behind the scenes by the complier, as well as the setter and getter. Essentially that code never should appear in your app.
In all of my iOS apps I've written thus far, I always declare my variables using #property in my header file and #synthesize VARIABLE_NAME = _VARIABLE_NAME; Since watching the lecture, I'm now confused as to if I should be using #synthesize in my code at all.
Should I just use the property declaration? What difference does it make, if any, if I use the synthesize declaration in my code?
Since Mr. Haggerty doesn't use it, then why do I? (considering he's sort of an iOS demi-god). I very much feel like it's bad form to do what I've been doing.
Anyone care to clarify that issue?

Xcode 4.0 Developer Preview 4 Release Notes. Adds default automatic synthesis of properties (iOS and 64-bit OS X). You don’t need the #synthesize directive in the implementation sections for the compiler to synthesize accessors for declared properties.
So
#synthesize ivar = _ivar;
is exactly same if you omit it.

There is no longer any need for synthesize. This was also covered in a WWDC session this year. Just use properties.

Not including "#synthesize VARIABLE_NAME = _VARIABLE_NAME" will do the exact same thing as if you actually included it, since the compiler will automatically add that if you don't add anything.

with Xcode 4.5 or up. The IDE write the #synthesize statement for you.
The #synthesize statement is only write the setter and getter for you.
that, _variable_name is the instant variable.
The variable_name is only a method that returns the value of _variable_name by default.
when using the variable = <Statement or value>. its calling thesetVarable_Namemethod to set the_variable_name` by default.
Hope it helped.

Related

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.

iOS call properties

I'm a beginner in iOS development and I'm currently watching couple courses online which explain the whole in the backscene getting and setting process.
Somebody thought me that when I'm initializing a variable I should use:
[self setX:1];
And in the rest of the code to acces this variabel I should use:
_x
instead of :
[self x]
The reason for this had something to do with reference counting, but now in the course the person tells me to never use the underscore for anything but in the automatic generated getter and setter?
I know about the dot notation. But concrete question is: "Can I call variabel with the getter and setter without the fear of memory leaks (I'm using ARC) instead of the underscore.
The underlying instance variable for that property is in fact _x. That is how auto synthesised properties work.
However you should consider using the accessors to set the property (using self.x = instead). See this link for more info on Reason to use ivars vs properties in objective c
Your ios version is ios6 that's why it will be direclty get _x.
When you define any property
#Property int x;
ios6 automaticall synthsize using _x; so dont worry you can used _x.

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.

Need explanation on #property/#synthesize in iOS

Not a complete noob I am quite new to iOS programming and to Ojbective-C. I mainly come from a background of C (DSP, Microcontrollers), Delphi XE2/Pascal , Visual Basic and Java (desktop and Android apps).
I mainly learned Cocoa with the book "Beginning iOS 5 Development", from Apress.
Recently I watched videos of the WWDC 2012 and went through some of their sample code, and I must say that I am confused of what is the proper way of writing my apps and more specifically with the #property/#synthesize words.
In the book most (not to say all) of the sample code uses to define a property as for example
ViewController.h
#property (strong, nonatomic) NSMutableArray *list;
ViewController.m
#synthesize list;
then all the code access synthesize list with
self.list
or even simply
list
Now in every WWDC code sample I read I see that programmers define a property but then, in the .m file they do things like
#synthesize list = _list;
and access sometimes
self.list
or
_list
I am confused. What is the correct practice ? As Apple programmers all use underscore I think I should do it that way but why the book did not ? Is there a difference between list and _list ? And more over, as I am in the same object why sometime use self.list and sometimes list/_list.
Sometimes they don't use #synthesize, I assume it's when they want to re-write their own accessors and mutators (which is never my case up to now).
I have read here and there on the web but nothing was clear enough to set my mind right, so I count on StackOverflow to bring light here.
Last but not least I prefer and answer based on current iOS 6 best practice/programming technique. Useless to tell me how to do it correctly in older iOS.
There is no correct way. There is only your preferred style.
The lastest compilers do an implicit synthesise on the property declaration.
#synthesize list = _list; .
Nothing is ever written in your code. It just happens.
However that doesnt stop you doing this explicitly.
#synthesize list = somethingelse;
So when you ask for a pointer to list via the accessor (self.list) you will get a pointer to somethingelse
In most cases NSMutableArray *thing = self.list is equivalent to NSMutableArray *thing = somethingelse
And just because Apple uses a style doesn't mean that you have to do it. Each company usually has their own coding style.
The main problem with using #synthesize list; is that it poses the risk that you can write either
self.list = thing or list = thing .
The former uses the sythesised setList: accessor while the latter doesn't and put the risk of related bugs in your code , though its not as bad with ARC as you dont get leaks happening for strong properties.
What ever style you use, keep it consistent and be aware of the effects of using an ivar directly list = thing as compared to using its accessor self.list = thing
This is a language feature that has had its usage evolve rapidly over the past few years, which explains the various forms. With the most recent tools, you can choose to ignore #synthesize and have things work reasonably.
The default behavior in that case produces the same effect as #synthesize list = _list;.

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