0

Possible Duplicate:
(Objective-)C ints always initialized to 0?

I have an interface

@interface MyInterface
{
   NSInteger _count;
}

@end

Then in my implementation I am just using is as

if (_count==0)
{
  //do somthing
}
_count++;

And it works i.e. the first time around when this is executed the value is in fact 0 even though I never initialized it to be zero.

Is it because the default value of NSInteger is 0?

Community
  • 1
  • 1
Java Ka Baby
  • 4,880
  • 11
  • 39
  • 51
  • 2
    When an Objective-C class is instantiated, all the instance variables are set to their initial values. It's done by the allocation mechanism. – Macmade Sep 16 '11 at 22:13

3 Answers3

4

Assuming you meant to write == instead of =, the answer is that all of the instance variables (ivars) of an Objective-C class get initialized to 0 or nil when the object gets created. See the question (Objective-)C ints always initialized to 0?.

If you actually wrote if (_count = 0) with a single =, then that's not doing what you expected -- it's assigning 0 to _count, and then testing if it's non-zero (the expression if (x) tests if x is non-zero). Since you just assigned 0 to it, it's not non-zero, so the test will always fail.

Community
  • 1
  • 1
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
1

change your if statement to

if (_count == 0)

remember double equals is comparison, single equals is assignment

Sean
  • 5,810
  • 2
  • 33
  • 41
1

you are using

if (_count=0)

this will set value 0 to variable _count, and if this action success, code between {} is executed

to test value of variable use comparison operator ==

if(_count == 0)
Marek Sebera
  • 39,650
  • 37
  • 158
  • 244