I have a method that gets called any time a control on my view changes and should update a UILabel. It has two UITextFields and two UISliders. First I check to see if either of the UITextFields are empty and if so, advise that they need to be filled in. Otherwise I get the difference between the UITextFields’ values and generate a couple of floats to use in my NSStrings.
I get a warning that message is not used and I get an error about the NSStrings (can’t remember now exactly what – I’m not at my Mac…)
And even when I chopped the messages down to something simple that worked, when delta == 0, it does the delta <= 0 message.
Oh, and the strings don’t put the values in where the % signs are, they just print the % signs.
I’ve been hacking at this too long and need help…
- (void)updateAdvice {
if ([chlorineSourceField.text isEqualToString:@""] || [poolVolumeField.text isEqualToString:@""]) {
NSString *message = [[NSString alloc] initWithString:@"Enter a chlorine source and pool volume."];
}
else {
int delta = [targetLabel.text intValue] - [startingLabel.text intValue];
float chlorineAmount = delta * [poolVolumeField.text intValue] * chlorineConstant;
float percentRemove = (1 - ([targetLabel.text floatValue] / [startingLabel.text floatValue]));
float gallonsRemove = percentRemove * [poolVolumeField.text intValue];
if (delta == 0) {
NSString *message = [[NSString alloc] initWithString:@"No adjustments necessary. You're on target"];
}
if (delta >= 0) {
NSString *message = [[NSString alloc] initWithFormat:@"To increase FC by %dppm, add %3.1f oz of %@.", delta, chlorineAmount, chlorineSourceField.text];
}
if (delta <= 0) {
NSString *message = [[NSString alloc] initWithFormat:@"You're above target already. Replace %d%% or %d gallons of water - or just wait for it to come down.", percentRemove*100, gallonsRemove];
}
}
adviceLabel.text = message;
[message release];
}
You are missing the
elsepart, thus all threeifstatements are being evaluated consecutively. Ifdelta == 0, it will satisfy all threeifstatements. Thus, the last allocation will overwrite the previous two. (And you’ll be leaking memory)Also, your
messagevariable is scoped as local to theifblock it’s declared into. You might want to move themessagedeclaration at the function level scope.As far as
%not working, you are using the instance initializerinitWithFormatwith the syntax for the class initializerstringWithFormat.initWithFormattakes the parameters for the formatted string in a separate parameter –arguments:. (Btw, it also requireslocale:)