问题
I have a picker view and I want the the things in it to be the tail numbers of the planes. I use this code, but I get the warning Loop will run once at most, (loop increment never executed)
, and then I get the error control may each end of non-void function.
What is wrong here?
CODE:
- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
for (NSInteger i = [[NSUserDefaults standardUserDefaults]integerForKey:@"planeNum"]; (i = 0); i--) {
NSString *dTailNumber = [NSString stringWithFormat:@"%@", [[NSUserDefaults standardUserDefaults]objectForKey:[NSString stringWithFormat:@"Plane%liTailNumber", i]]];
return dTailNumber;
}
}
回答1:
The reason you get the warning
Loop will run once at most, (loop increment never executed)
Is because you have an unconditional return
in the body of the loop. On the first execution of the loop, it will return
out of the method before the loop increment is reached.
The reason you get the
control may reach the end of a non-void function
is because there's no guarantee for this function to ever return anything. What if the loop executes 0 times? Then the method never returns anything, which isn't okay since it's declared as returning an NSString
.
回答2:
Way too much thinking about it. It is quite simple (took me a minute to figure it out too!)
- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
// set a blank string
NSString *dTailNumber = @"";
for (NSInteger i = [[NSUserDefaults standardUserDefaults]integerForKey:@"planeNum"]; (i = 0); i--) {
// no need to declare here now
dTailNumber = [NSString stringWithFormat:@"%@", [[NSUserDefaults standardUserDefaults]objectForKey:[NSString stringWithFormat:@"Plane%liTailNumber", i]]];
// this is removed from loop
// return dTailNumber;
}
// instead return here
return dTailNumber;
}
The method itself will first make sure (self) will return the appropriate property (NSString *)...BEFORE IT RUNS ANY UNDERLYING CODE...period! I always forget that the compiler simply checks for everything needed and then runs all inner functions! Pretty cool when you figure it out!
来源:https://stackoverflow.com/questions/24586891/loop-will-run-once-at-most-loop-increment-never-executed