嘿,堆栈溢出!如果您在没有它的情况下理解我的问题,请随意跳过代码;或多或少只是为偶然发现该线程的学习者提供一些代码。
1)重复使用标签是否风格不佳?
2) 对于 switch 语句,在每种情况下始终使用大括号是一种好习惯吗?我这样做是因为我很清楚旧的 ARC 更改会导致在案例块中分配变量时发生“switch case is in protected scope”错误。我问的原因与 #1 相同:我希望在不养成不良风格习惯的情况下收紧我的代码。
我只是在整理这个例子来涵盖两者,所以请原谅拼写错误/等:
登录.m
-(void)irrelevantSignInMethod
{
//Failed login
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Sorry!" message:@"Log in failed" delegate: self cancelButtonTitle:@"OK" otherButtonTitles:@"Try Again", nil];
[alert show];
[alert setTag:1];
...
//Confirmed login
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Sweet!" message:@"You've logged in!" delegate: self cancelButtonTitle:@"Sweet!" otherButtonTitles:nil, nil];
[alert show];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:signInUsername.text forKey:@"username"];
[defaults synchronize];
[alert setTag:2];
}
-(void)irrelevantSignUpThenInMethod
{
....
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Sweet!" message:@"You've registered and logged in!" delegate: self cancelButtonTitle:@"Sweet!" otherButtonTitles: nil];
[alert show];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[alert setTag:3];
//Just here to remind code-borrowers to store username somewhere
[defaults setObject:signInUsername.text forKey:@"username"];
[defaults synchronize];
//Here's where the question lies; is there any reason to not tweak to [alert setTag:2], shaving an if statement in the clickButtonAtIndex method?
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
switch (alertView.tag)
{
case 1:
{
([[alertView buttonTitleAtIndex:buttonIndex] isEqualToString:@"Try Again"]))
{
//I always add an alert with "Try Again" in case the log in failed
UITextField *username = [alertView textFieldAtIndex:0];
UITextField *password = [alertView textFieldAtIndex:1];
signInUsername.text = username.text;
signInPassword.text = password.text;
[self attemptSignIn];
break;
}
}
case 2:
{
[self loggedIn];
break;
}
case 3:
{
//Here's where question #1 lies; is there any reason to not just assign both alerts the same tag (2) earlier and not need a 3rd case?
[self loggedIn];
break;
}
case 4:
{
//Forgot password scenario. Too lazy to write how I do this out - but will answer if anyone PMs me - those borrowing this code should be prepared for this situation!
break;
}
default:
{
break;
}
}
}
是的,我意识到代码可能不是必需的——但谁知道呢,有人可能会从看到基本的登录结构中受益。如果我之前不清楚,我将详细说明我的问题:我可以继续分配标签 2 两次并简化 clickedButtonAtIndex 方法吗?我是一名 CS 专业的,并且在几个学期前就学习过这方面的内容,所以我不记得是否有任何澄清。我怀疑存在区分的技术原因,而且我只关注简洁的代码,但我不想开始养成打破“这是经典方式”形式的习惯。尤其是当我在风格上评分并与其他人一起完成更大的项目时。我知道这是一个小问题,但我发现自己想知道大多数人是如何解决这个问题的,并且希望与您的专业知识进行对话。
3)我知道这很糟糕(编辑:糟糕)礼仪,但我希望至少有 1 次“投票”,所以我有资格开始“投票”,因为我每天无数次使用来自其他线程的知识,并且作为一个潜伏者五年多来,我觉得是时候开始用非常有价值的互联网积分奖励乐于助人的人了。
感谢您的时间堆栈溢出。您确实是理解概念、发现解决方案和开发开发人员的最佳人选。