Local variables set to nil? (Objective-C)

12,460

With ARC enabled, your Objective-C object pointer variables will be set to nil regardless of where you create them.

Without ARC, and for built in C types, your variables will not be initialized.

Instance variables of Objective-C objects are always set to 0 (or nil) when you allocate an object.

Statics are set to 0.

I've gotten in the habit of always giving a default value to variables, though. It's been a good habit to have.

Share:
12,460
stumped
Author by

stumped

:D

Updated on June 06, 2022

Comments

  • stumped
    stumped about 2 years

    I'm reading a book on Objective-C and the author said that if local variables aren't assigned a value they will be set to nil, but static variables will be set to zero. So, I set up int a and didn't assign it a value. Then NSLog(@"%i", a) to display it and a was displayed as zero. I was a little confused on that and I was wondering if someone could clarify it for me?

  • Ricardo
    Ricardo about 10 years
    What about C types with ARC? What about if I have a BOOL when using ARC? Thanks!
  • wbyoung
    wbyoung about 10 years
    @Ricardo they should be handled according to C rules. Statics will be 0 and all others should be considered garbage.
  • Ricardo
    Ricardo about 10 years
    Thanks. So, something like @property (nonatomic, assign) BOOL flag; is gargabe, isn't it? because is not staitc. However in my app I see it's 0 always. I don't have these rules very clear.
  • wbyoung
    wbyoung about 10 years
    @Ricardo the property is backed by an instance variable, not a local variable. So it falls into the instance variable rule and will be set to 0/FALSE/nil.
  • palmi
    palmi over 6 years
    For anyone looking for a source to this answer see Apple's document Transitioning to ARC Release Notes. Specifically the section titled Stack Variables Are Initialized with nil. developer.apple.com/library/content/releasenotes/ObjectiveC/‌​…