這篇練習要達成的是一個小型但完整的互動:介面上有三個 UISwitch 分別控制「小寫字母」「大寫字母」「數字」是否納入字元池,一個輸入框指定密碼長度,點擊按鈕後依設定即時生成隨機密碼並回顯。所有控件透過 Interface Builder 以 IBOutlet / IBAction 連接,而不是純手寫 UI。
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
@interface ViewController : UIViewController {
IBOutlet UITextField *passwordlength;
IBOutlet UITextField *password;
IBOutlet UISwitch *includeUpperCase;
IBOutlet UISwitch *includeLowerCase;
IBOutlet UISwitch *includeNumbers;
}
@property (nonatomic, retain) UITextField *passwordlength;
@property (nonatomic, retain) UITextField *password;
@property (nonatomic, retain) UISwitch *includeUpperCase;
@property (nonatomic, retain) UISwitch *includeLowerCase;
@property (nonatomic, retain) UISwitch *includeNumbers;
- (IBAction)onPasswordButtonClick:(id)sender;
@end
這裡有個值得注意的細節:UISwitch 的目前狀態不需要另外用變數記錄,直接讀取 switch.on 即可,因為控件本身就是狀態的持有者。這是 IB 連接相比純程式碼建立 UI 的便利之處。
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if (textField == password) {
[password resignFirstResponder];
}
if (textField == passwordlength) {
[passwordlength resignFirstResponder];
}
return YES;
}
記得在 Storyboard 中把兩個 UITextField 的 delegate 連到 ViewController,否則這個方法不會被呼叫。另外,UITextField 的 Return Key 建議設為 Done。
#define RANDOM_SEED() srandom(time(NULL)) // 以最小值、最大值與隨機數計算,回傳整數 #define RANDOM_INT(_MIN_, _MAX_) ((_MIN_) + random() % ((_MAX_ + 1) - (_MIN_)))
- (IBAction)onPasswordButtonClick:(id)sender {
// 1. 讀取使用者輸入的長度
NSInteger iPasswordLength = [passwordlength.text intValue];
// 2. 讀取三個 Switch 的狀態
BOOL bIncludeLowerCase = includeLowerCase.on;
BOOL bIncludeUpperCase = includeUpperCase.on;
BOOL bIncludeNumbers = includeNumbers.on;
// 3. 準備候選字元集
NSString *lowercaseChars = @"abcdefghijklmnopqrstuvwxyz";
NSString *uppercaseChars = @"ABCDEFGHIGKLMNOPQRSTUVWXYZ";
NSString *numbersChars = @"1234567890";
RANDOM_SEED();
// 4. 依 Switch 狀態逐步組出字元池
NSString *passwordChars = @"";
NSString *passwordText = @"";
if (bIncludeLowerCase) {
passwordChars = [NSString stringWithFormat:@"%@%@", passwordChars, lowercaseChars];
}
if (bIncludeUpperCase) {
passwordChars = [NSString stringWithFormat:@"%@%@", passwordChars, uppercaseChars];
}
if (bIncludeNumbers) {
passwordChars = [NSString stringWithFormat:@"%@%@", passwordChars, numbersChars];
}
// 5. 從字元池中等概率取字,組出最終密碼
for (NSInteger i = 0; i < iPasswordLength; i++) {
int index = RANDOM_INT(0, [passwordChars length] - 1);
NSRange range = NSMakeRange(index, 1);
NSString *passwordChar = [passwordChars substringWithRange:range];
passwordText = [NSString stringWithFormat:@"%@%@", passwordText, passwordChar];
}
// 6. 回顯結果
password.text = @"";
password.text = passwordText;
}
這個範例使用 MRC,因此 dealloc 中需逐一釋放 outlet:
- (void)dealloc {
[passwordlength release];
[password release];
[includeNumbers release];
[includeLowerCase release];
[includeUpperCase release];
[super dealloc];
}


表面上是「生成隨機密碼」,實際練的是三件事:
若要再往前一步,可以替這個元件加上密碼強度提示、或把 substringWithRange: 的逐字串接改成 NSMutableString 的 appendFormat,避免長密碼時反覆建立新字串物件。