tags:

views:

34

answers:

2

Just trying to create a simple method that counts up 1 on the tally when the button is pressed. My knowledge is extremely limited and I am pretty sure that my problem is somewhere in the method implementation:

-(IBAction) updateTally:(id) sender {
    NSString *text;
    int total = 0;
    total = total + 1;
    text=[[NSString alloc] initWithFormat: @"%i", total];
    lblTally.text = text;
}

I have done the necessary interface declarations for the lblTally UILabel and the updateTally method. I suspect that there is some sort of an NSString/int/%i/%@ mixup that I am making but I'm not sure how to fix it. When I run the program as it currently is it displays a 0 in the lblTally label field on the iphone. When I press the button it then displays a 1 in that field. However, if I continue to press the button - nothing happens, it just remains a 1. How do I make it count up as I continually press the button over and over?

+1  A: 

You are re-initialising the total variable each time the method runs.

int total = 0;

Move than line of code outside of the method. I dont do apple development but it'll be something like:

int total = 0;
-(IBAction) updateTally:(id) sender {
    NSString *text;
    total = total + 1;
    text=[[NSString alloc] initWithFormat: @"%i", total];
    lblTally.text = text;
}
geoff
@geoff, the total should be a member of his class; not a global variable.
Michael Aaron Safyan
@Michael - You're right, but the point is that the declaration needs to be outside his method...I've edited my answer.
geoff
+2  A: 

The problem is that you are reinitializing the total in each updateTally. You need to either store the tally in a member variable or extract the existing tally from the string, update it, then write it back to the string.

- (IBAction) updateTally:(id) sender
{
    int oldtally = [lblTally.text integerValue];
    int newtally = oldtally + 1;
    lblTally.text = [NSString stringWithFormat:"%d",newtally];
}

I should also point out that your current code has a memory leak (you invoke alloc/init, but then you don't invoke release after you have assigned the result to the lblTally.text variable). You should either invoke [text release] after lblTally.text = text, or you should use stringWithFormat like I have used above, which uses autorelease so that the string does not need to be explicitly released (since it will be automatically released).

Michael Aaron Safyan
This works, thank you very much for the help. Unfortunately, I don't understand why it works. Why wouldn't the first line work as simply "int oldtally = lblTally.text" ?????
Rob
The reason "int oldtally = lblTally.text" wouldn't work, is because lblTally.text is a string. You need to convert it to an integer, by invoking its "integerValue" method, which reports the integer represented by the string (assuming the string actually represents an integer-- you get an error if it doesn't).
Michael Aaron Safyan