tags:

views:

189

answers:

4

I.e., does ObjectiveC behave like C, in that if you create a pointer eg:

NSString* c;

Does c point to nil, or to the random value in the memory area that was reserved for it?

In other words, do pointers get pre-initialized, or do I need to do that myself? As I said, I'm aware this is not the case in C/C++, but I'm wondering if there's some ObjC magic here or not.

+6  A: 

Class instances variables in Objective-C are guaranteed to be initialized to their empty value (0, nil, etc ...)

JaredPar
Brilliant - cheers. Unfortunately, that means that my bug is not where I thought it was.
Chaos
More specifically, the memory space for a class is zeroed when it is allocated. Pointers in a method or function work exactly like in C.
Chuck
+1  A: 

They are nil, and you are allowed to assume this, for instance by testing:

if (nil == myVariableIHaventInitialisedYet)
{ 
  myVariableIHaventInitialisedYet = [SomeThingIMightMake initWithLove];
}
Alex Brown
Nice yoda code!
toxaq
+3  A: 

Class instance variables and static/global variables get initialized to nil/NULL/0/false as appropriate.

However local variables are not initialized.

Peter N Lewis
A: 

Watch for local variables on this one. They don't get initialized to nil, so make sure they've been init'd somewhere before using it if you didn't init to nil in your declaration. As Peter says, class, instance and static are init'd to nil for you so no worries there.

Normally no issues, but in particular it'll make a difference in calls with pointer references passed in (like NSError **).