简体   繁体   English

简单的iPhone理货方法问题

[英]Simple iPhone tally method question

Just trying to create a simple method that counts up 1 on the tally when the button is pressed. 只是试图创建一个简单的方法,当按下按钮时,该计数在计数上加1。 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. 我已经为lblTally UILabel和updateTally方法完成了必要的接口声明。 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. 我怀疑我正在制作某种NSString / int /%i /%@混合,但是我不确定如何解决。 When I run the program as it currently is it displays a 0 in the lblTally label field on the iphone. 当我按当前方式运行程序时,它在iPhone的lblTally标签字段中显示为0。 When I press the button it then displays a 1 in that field. 当我按下按钮时,它将在该字段中显示1。 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。当我不断反复按下按钮时,如何使它计数?

The problem is that you are reinitializing the total in each updateTally. 问题是您要在每个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). 我还应该指出,您当前的代码存在内存泄漏(您调用alloc / init,但是在将结果分配给lblTally.text变量之后,您不调用release了)。 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). 您应该在lblTally.text = text之后调用[text release],或者应该像我上面使用的那样使用stringWithFormat,它使用自动释放,因此不需要显式释放字符串(因为它将被自动释放)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM