Page 1 of 1 [ 6 posts ] 

Madbones
Veteran
Veteran

User avatar

Joined: 7 Mar 2010
Age: 29
Gender: Male
Posts: 777
Location: In the zone

28 Sep 2011, 6:27 pm

I have the following code:

Code:
-(IBAction) buttonPress{
int var = 1;
var++;
NSLog(@"The var is:%@", var);
}

For some reason it is only going up to 2.
Why is this?
Im sorry if this is an obvious mistake, im really tired, so im not thinking too clearly.



mcg
Veteran
Veteran

User avatar

Joined: 26 Jan 2010
Age: 36
Gender: Male
Posts: 538
Location: Sacramento

28 Sep 2011, 6:57 pm

because var is a local variable which falls out of scope after the call to NSLog.



Madbones
Veteran
Veteran

User avatar

Joined: 7 Mar 2010
Age: 29
Gender: Male
Posts: 777
Location: In the zone

28 Sep 2011, 7:03 pm

mcg wrote:
because var is a local variable which falls out of scope after the call to NSLog.

But I have done this before successfully (The variable is not named var.That was an example).
What would be the correct way?



mcg
Veteran
Veteran

User avatar

Joined: 26 Jan 2010
Age: 36
Gender: Male
Posts: 538
Location: Sacramento

28 Sep 2011, 9:37 pm

Madbones wrote:
But I have done this before successfully (The variable is not named var.That was an example).

The name doesn't matter. What matters is that it is declared inside a method and falls out of scope as soon as program flow returns from that method (the stack frame in which it resides is obliterated, not to be recreated until the next call to your method).

Madbones wrote:
What would be the correct way?
I'm not sure of your exact circumstances, but if your object is persistent, I would just declare an instance variable for your counter in the same class where you declare that method. Instance variables maintain their value until the object in which they reside is destroyed.



MDM
Snowy Owl
Snowy Owl

User avatar

Joined: 30 May 2010
Age: 32
Gender: Male
Posts: 126
Location: Montana, USA

28 Sep 2011, 10:35 pm

Declare var in your interface file. Don't declare it on a local scope if you don't want it to become non-existant past that local scope. You could also declare it as static or declare it globally.



peterd
Veteran
Veteran

User avatar

Joined: 25 Dec 2006
Age: 73
Gender: Male
Posts: 1,375

29 Sep 2011, 7:49 am

Quote:
Declare var in your interface file. Don't declare it on a local scope


And set it to one when you declare it, or in ...didLoad... - not in the same method that you're adding one to it.