Local variables set to nil? (Objective-C)
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.
Comments
-
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. ThenNSLog(@"%i", a)
to display it anda
was displayed as zero. I was a little confused on that and I was wondering if someone could clarify it for me? -
Ricardo about 10 yearsWhat about C types with ARC? What about if I have a BOOL when using ARC? Thanks!
-
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 about 10 yearsThanks. 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 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 over 6 yearsFor 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/…