Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are primitive instance variables initialized by default in Objective-C?

In the following code, is it safe to use _test and expect it to have a vaue of NO? Or do I need to always explicitly initialize it in - (id)init?

@implementation Test {
    BOOL _test;
}
like image 932
rid Avatar asked May 18 '12 12:05

rid


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.

Are instance variables primitive?

A primitive-type variable can store exactly one value of its declared type at a time. Primitive-type instance variables are initialized by default. Variables of types byt e, char , short , int , long , float and double are initialized to 0 .

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.


1 Answers

It is safe to assume that all instance variables will be initialized to 0.

This however is not the case for locally/method scoped variables which, if not manually initialized, will point to junk.

For future reference, as Rob Napier points out, this can be found in the documentation for + (id)alloc:

The isa instance variable of the new instance is initialized to a data structure that describes the class; memory for all other instance variables is set to 0.

like image 166
mmccomb Avatar answered Sep 19 '22 21:09

mmccomb