2

During the initial days of my development, I started always creating instance variables in every programs I wrote. But after getting to the power of properties, I felt we need not use iVars.

But at times when I had to debug the code, I found the difficulties in debugging custom entities' values due to the iVars being missing.

Now I am planning to have iVars on all the Custom interface implementations.

Please confirm if what I have been doing is a good practice, does it have a trade-off?

Is there any other reason we need to use iVars in Objective C?

RK-
  • 12,099
  • 23
  • 89
  • 155

3 Answers3

5

You aren't "not using" iVars by using properties (most of the time). You are just letting the compiler generate them for you. I use private and protected iVars often for things that I don't want exposed to outside unrelated classes (flags, etc). Properties are just iVars coupled with defined getters (and setters possibly). I don't understand what you think you are gaining by avoiding explicit iVars.

borrrden
  • 33,256
  • 8
  • 74
  • 109
  • I was not gaining anything by avoiding explicit iVars. Just saved few lines of code – RK- Jun 11 '12 at 12:33
3

First of all, your properties are always going to be backed by instance variables unless you have some dynamic runtime stuff going on (for example with subclasses of NSManagedObject) or the property is fully implemented with a custom getter/setter.

When you synthesize a property, an instance variable is created for you. You can declare the instance variables explicitly in your @interface {} declaration, but it is no longer necessary to do this.

Generally you should prefer to use properties rather than instance variables, but there are situations where you have to access the instance variable directly. For example, the best practice for init methods is to avoid using property accessors to set up the object, since a subclass could override the property accessors and try and do stuff before the object is fully initialized. Custom getter/setter methods also need to use instance variables directly.

Mike Weller
  • 45,401
  • 15
  • 131
  • 151
2

When you declare property and a @synthesize statement the compiler will take care about creating the instance variable with in the accessor methods. please refer this link for more info Should I use ivars in Objective-C?

Community
  • 1
  • 1
Malek_Jundi
  • 6,140
  • 2
  • 27
  • 36