I was wondering if attributes were automatically set to nil
during an object's initialization or they have random values?
Asked
Active
Viewed 500 times
1

jscs
- 63,694
- 13
- 151
- 195
3 Answers
4
All instance variables are guaranteed to be initialized to nil or zero. This goes for non-object iVars as well, (int, BOOL, float).

Joshua Weinberg
- 28,598
- 2
- 97
- 90
-
You might want to hyphenate non-object to clarify the phrase "non object iVars"; for a second I thought you were saying non-iVars are automatically initialized to 0/nil. – NSGod Dec 25 '10 at 02:13
1
If this question is indicative of Objective-C, I'd say that you should initialize all values of a variable when you declare them.
Explicitly initializing variables when they're declared gives you two benefits:
- There is no ambiguity in what the value of the variable is.
- Readability for others who read your code.

Community
- 1
- 1

David Weiser
- 5,190
- 4
- 28
- 35
-
That's a slightly different use-case, because of the difference between stack allocation (which is what that question is about) and heap allocation (which is what this question is about). – Dave DeLong Dec 25 '10 at 02:54
-
There's nothing in the question that makes me think that. Objects can be declared on the stack too, right? – David Weiser Dec 25 '10 at 03:03
-
except for one exception, no. You cannot have stack-allocated objects in Objective-C (* without doing crazy stupid stuff). The one exception is a block, which is allocated on the stack, and then subsequently copied to the heap Blocks behave and are considered objects. WRT to the question, objects are allocated on the heap using `calloc()`, which zeros the chunk. However, a stack frame is *not* zeroed when it is pushed. As such, any local variables declared in the stack frame have the initial value of whatever was in that memory slot before (unless you initialize them otherwise). – Dave DeLong Dec 29 '10 at 03:55
-1
In Java, the data members of a class are set their default values. I.e string = null ,int =0.

Programmer
- 6,565
- 25
- 78
- 125