0

我正在尝试将五个整数相加UITextFields并将它们发布到UILabel.

这是我尝试过的代码,但它不能正常工作。标签中显示的数字不是我的文本字段的总和。我也尝试过发布到文本字段而不是标签,结果相同。构建时没有错误或警告。

int val = [textfield1.text intValue]
val = val+[textfield2.text intValue];
val = val+[textfield3.text intValue];
val = val+[textfield4.text intValue];
val = val+[textfield5.text intValue];

NSString *labelStr = [[NSString alloc] initWithFormat:@"%i", val];

label.text = labelStr;

代码有问题吗?替代代码?感谢所有答案!

4

1 回答 1

0

The code looks more or less right to me, aside from the memory leak. You should review the memory management rules and fix your leak.

My guess is that the numbers you entered add up to a number that is outside the range of an int. Entering, say, 1000000000 (10**9) in each of the five fields would be one way to pull this off, on any machine where an int is 32 bits (including, currently, the iPhone-OS devices).

Depending on the purpose of your app, you may be able to simply cap the five input fields; if the highest value that makes any sense is less than one-fifth (for five fields, and that's assuming they all have the same cap) of the maximum int, overflow is impossible.

If a cap won't solve the problem completely, try a different type. If the values should never be negative, use an unsigned type. Otherwise, try long long, or either of the floating-point types, or use NSDecimalNumber objects.

Of course, I could be completely wrong, since you didn't say what numbers you entered or what the result was. If it was zero, make sure that you hooked up your outlets in IB; if you forgot to do that, they contain nil, which, when you ask it for text, will return nil, which, when you ask it for an intValue, will return 0, and 0 + 0 + 0 + 0 + 0 = 0.

于 2010-02-14T17:02:50.863 回答