## iOS 处理方法中的可变參数
近期写了一个自己定义的对话框
的demo,想模仿系统的UIAlertView的实现方式。对处理可变參数
的时候,遇到了小问题,于是谷歌了一下。写下了处理问题的方法。记录下来,以备后需。
代码实现
- (instancetype)initWithTitle:(NSString *)title message:(NSString *)message delegate:(id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... { if (self = [super init]) { self.title = title; self.delegate = delegate; self.frame = CYScreen.bounds; // 获取可变參数的值 if (![self isBlankString:cancelButtonTitle]) { [self.buttonTitles addObject:cancelButtonTitle]; } NSString *str; va_list list; if(otherButtonTitles) { // 1.取得第一个參数的值 CYLog(@"%@", otherButtonTitles); [self.buttonTitles addObject:otherButtonTitles]; // 2.从第2个參数開始。依此取得全部參数的值 va_start(list, otherButtonTitles); while ((str = va_arg(list, NSString *))){ CYLog(@"%@", str); [self.buttonTitles addObject:str]; } va_end(list); } CYLog(@"%@", self.buttonTitles); } return self;}
方法调用
- (IBAction)showDialog { CYAlertView *alert = [[CYAlertView alloc]initWithTitle:@"我的提示" message:@"消息正文" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", @"XXX", @"YYY", nil]; alert.containerView = [self createDemoView]; [alert show];}
打印结果
2015-07-06 15:54:26.422 CYCustomAlertView[358:42937] 确定2015-07-06 15:54:26.424 CYCustomAlertView[358:42937] XXX2015-07-06 15:54:26.424 CYCustomAlertView[358:42937] YYY2015-07-06 15:54:26.425 CYCustomAlertView[358:42937] ( 取消, 确定, XXX, YYY,)