iOS call properties - ios

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.

Related

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.

Objective C - Add property in runtime

I'd like to add an ivar to an existing objective-c class in runtime, but documentation states that an ivar cannot be an existing class, so I think property could still solve my issue.
As stated here class_addProperty(...) returns true, but when I try to access the ivar by it's name (or the property name) it always returns nil. What could be the issue causing this to happen?
You won't be able to add an ivar to the class at runtime. You can think of the class, and its ivars, as something like a C struct. It's layout is defined at compile time.
You can add properties at runtime (since these are just methods), and you can implement their getters and setters, but you'll need to come up with a different way to store any data that they represent.
Are you looking for something similar with some other programming language?
it looks like adding properties in AS3, but objc think the best would you use to store NSDictionary objects by keys.

Using #synthesize in ios Application

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.

IOS: When declaring properties in a .h what's the difference between self.var and just var? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Objective-C - When to use 'self'
I needed a variable to be passed from one view to another so I made a property called StringC in the .h and accessed it using self.StringC (that part worked).
I also need some arrays that are accessible throughout the view but I'm using them differently.
For instance I have lvLabelArray and I'm using
self.lvLabelArray=[[NSMutableArray alloc]init];
and then later I'm using
[lvLabelArray addObject:LabelText];
Is there a difference between that and
[self.lvLabelArray addObject:LabelText];
?
Sorry I don't know the terms for those kinds of variables.
There is an important difference there.
self.attribute goes through the object's getter or setter function, as appropriate. That allows you to set up initial values, trigger update messages, or anything else.
Accessing "attribute" directly goes straight to the underlying variable, so you bypass all that. As a result, it's definitely the less-preferable way of working.
A common way of avoiding this confusion, and just plain mistakes, is to rename the underlying variable. Instead of just "#synthesize attribute", use "#synthesize attribute = _attribute". This will create the getter and setter methods as before, but they'll the underlying variable is named "_attribute". That means that trying to use "attribute" without "self" will trigger a compiler error.

Difference between _ and self. in Objective-C

Is there a difference between using the underscore and using the self keyword in Objective-C when calling an #property?
Property declaration:
#property (weak, nonatomic) NSString *myString;
Calling #synthesize on the property:
#synthesize myString = _myString;
Is there a difference if I want to use it in my code? When? In the getter/setter?
self.myString = #"test";
_myString = #"test";
self.myString = #"test"; is exactly equivalent to writing [self setMyString:#"test"];. Both of these are calling a method.
You could have written that method yourself. It might look something like this:
- (void)setMyString:(NSString*)newString
{
_myString = newString;
}
Because you used #synthesize, you don't have to actually bother writing that method, you can just allow the compiler to write it for you.
So, from looking at that method, it looks like calling it will do the exact same thing as just assigning a value to the instance variable, right? Well, it's not so simple.
Firstly, you could write your own setter method. If you do so, your method would get called, and it could do all sorts of additional things as well as setting the variable. In that case, using self.myString = would call your method, but doing _myString = would not, and thus different functionality would be used.
Secondly, if you ever use Key Value Observing, the compiler does some very clever tricks. Behind the scenes, it subclasses your class, and overrides your setter method (whether it's one you wrote yourself or one generated by synthesize), in order to make the calls to willChangeValueForKey: that are needed for Key Value Observing to work. You don't need to know how this works (although it's quite interesting if you want some bedtime reading!), but you do need to know that if you want Key Value Observing to work automatically, you have to use setter methods.
Thirdly, calling the setter method even if you're relying on synthesize to write one gives you flexibility for the future. You might want to do something extra whenever a value is changed, and at the point you discover you want to do that, you can manually write a setter method — if you're in the habit of always using self.myString =, then you won't need to change the rest of your code to start calling the new method!
Fourthly, the same applies to subclasses. If someone else was to subclass your code, if you use the setters then they could override them to adjust the functionality.
Any time you access the instance variable directly, you're explicitly not providing a way for extra functionality to be hooked in at that point. Since you or someone else might want to hook in such functionality in the future, it pays to use the setters all the time, unless there's a good reason not to.
You are correct - the first version (self.myString) calls the synthesized getter/setter and the second version access the private member variable directly.
It looks like you are using ARC, so in that case it doesn't make that much of a difference. However, if you aren't using ARC, it can make a difference as assigning to the private member directly won't trigger the automatic retain/release or copy/release logic that is generated for you by using synthesize.
The _ (underscore) is simply a convention, as explained in this question.
When you don't prefix a property access with self., you are accessing the underlying variable directly, as in a c struct. In general, you should only ever do this in your init methods and in custom property accessors. This allows stuff like computed properties and KVC to work as intended.
There is a tip not mentionend, the access using underscore is faster and the access using self is safer (KVC). Maybe this can summarise when you have to use each one.

Resources