开发者

Simple iPhone tally method question

开发者 https://www.devze.com 2022-12-28 16:46 出处:网络
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 impleme

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开发者_如何学JAVA = 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?


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).


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消