Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are instance variables set to nil by default in Objective-C?

I'm sorting out some memory issues with my iPhone app and I've just been thinking about some basics. If I setup an ivar and never end up using it in the lifespan of my object, when I call dealloc on it, will that cause a problem? E.g.

@interface testClass {     id myobject; } @property (nonatomic, retain) id myobject; @end  @implementation testClass @synthesize myobject; - (id)init {     ...     // Do I have to set myobject to nil here?     // So if myobject isn't used the dealloc call to nil     // will be okay? Or can you release the variable without     // having set every object to nil that you may may not use      ... }  ...  // Somewhere in the code, myobject may be set to // an instance of an object via self.myobject = [AnObject grabAnObject] // but the object may be left alone  ...  - (void)dealloc {     [myobject release];     [super dealloc]; } @end 
like image 878
Michael Waterfall Avatar asked Nov 23 '09 23:11

Michael Waterfall


People also ask

Are instance variables initialized by default?

Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and for object references it is null. Values can be assigned during the declaration or within the constructor. Instance variables can be accessed directly by calling the variable name inside the class.

What is instance variable Objective C?

An instance variable is a variable that exists and holds its value for the life of the object. The memory used for instance variables is allocated when the object is first created (through alloc ), and freed when the object is deallocated.

Can an instance variable be null?

An instance variable can also be a variable of object type. For such variables, the default initial value is null.

How do you find nil in Objective C?

Any message to nil will return a result which is the equivalent to 0 for the type requested. Since the 0 for a boolean is NO, that is the result. Show activity on this post. Hope it helps.


2 Answers

Instance variables are initialized to 0 before your initializer runs..

like image 140
Chuck Avatar answered Oct 12 '22 16:10

Chuck


Yes, ivars are always initialized to 0/nil/NULL/NO/etc.

However, if it helps you understand what's going on, go for it. The performance impact is negligible. You don't need to do it, but it won't cause any problems if you do.

like image 24
BJ Homer Avatar answered Oct 12 '22 15:10

BJ Homer