我有一个包含 3 个文本字段的 View :
- 当前密码
- 新密码
- 确认新密码
要求是,检查这些密码的有效性,如果不满足条件,会有一个alert view popup。
- 如果用户输入错误的当前密码
- 新密码必须超过8个字母
- 新密码必须匹配
我用了if
-else
但是好像不太合适,改用switch
-case
.但它仍然不起作用。
我的代码:
NSString *textFromBox1 = [stringArray objectAtIndex:0];
NSString *textFromBox2 = [stringArray objectAtIndex:1];
NSString *textFromBox3 = [stringArray objectAtIndex:2];
enum ErrorCase{
oldPasswordCase,
newPasswordLength,
newPasswordCheck,
};
enum ErrorCase error;
if ([textFromBox1 length] < 2) {
error = oldPasswordCase;
} else if ([textFromBox2 length] < 8) {
error = newPasswordLength;
} else if (textFromBox2 != textFromBox3) {
error = newPasswordCheck;
}
switch (error) {
case oldPasswordCase:
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"過ち"
message:@"現在のパスワードが間違っています。"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
break;
case newPasswordLength:
{
UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:@"過ち"
message:@"パスワードを8文字以上で入力してください。"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert2 show];
}
break;
case newPasswordCheck:
{
UIAlertView *alert3 = [[UIAlertView alloc] initWithTitle:@"過ち"
message:@"新しいパスワードとパスワード(確認)が間違っています。"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert3 show];
}
break;
default:
break;
}
最佳答案
在 Objective-C 中,switch
语句中的参数必须是整数。
使用 NS_ENUM
宏将枚举声明为整数
typedef NS_ENUM (NSInteger, ErrorCase) {
oldPasswordCase,
newPasswordLength,
newPasswordCheck,
};
然后声明错误变量
ErrorCase error;
正如 Mateusz 的回答中提到的,您必须使用 isEqualToString
来比较两个字符串。
编辑:您的 if - else
链并不详尽,这可能会导致意外行为。要么添加默认的 none
情况并将其分配给 error
要么确保 if - else
链考虑所有情况(感谢 Idali提示)。
关于ios - 在 Objective-C 上使用 Enum 和 Switch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38866715/