iOS可变参数va_list
需求:
用"/"拼接三个字符串,字符串为空则不拼接,有下边两种实现方式
一、if else的实现方式
+ (NSString *)getGoodsRuleWithCarLength:(NSString *)carLength andCarType:(NSString *)carType andSpecialRequire:(NSString *)specialRequire andEntrance:(TYTGoodsRuleEntrance)entrance{
NSString *goodsRule = nil;
if(carLength.length > 0){
if(carType.length > 0){
if(specialRequire.length > 0){
goodsRule = [NSString stringWithFormat:@"%@/%@/%@",carLength,carType,specialRequire];
}else{
goodsRule = [NSString stringWithFormat:@"%@/%@",carLength,carType];
}
}else{
if(specialRequire.length > 0){
goodsRule = [NSString stringWithFormat:@"%@/%@",carLength,specialRequire];
}else{
goodsRule = [NSString stringWithFormat:@"%@",carLength];
}
}
}else{
if(carType.length > 0){
if(specialRequire.length > 0){
goodsRule = [NSString stringWithFormat:@"%@/%@",carType,specialRequire];
}else{
goodsRule = [NSString stringWithFormat:@"%@",carType];
}
}else{
if(specialRequire.length > 0){
goodsRule = [NSString stringWithFormat:@"%@",specialRequire];
}else{
goodsRule = @"";
}
}
}
return goodsRule;
}
二、可变参数的方式
//创建NSString的分类
/**
* 用斜线拼接参数
* count为参数个数,其它参数必须是NSString类型(可为nil)
* eg.需要拼接三个字符串 长、宽、高为 "长/宽/高" 方法调用方式为[NSString splicWithSlantParamsCount:3, @"长", @"宽", @"高"];
*/
+ (NSString *)stringSplicWithSlantParamsCount:(int)count,...{
if(count < 1){
return @"";
}
int index = 0;
va_list args;
va_start(args, count);
//拼接后的字符串
NSString *paramSum = @"";
NSString *otherParam;
//循环到结尾就停止循环
while(index<count){
index ++;
otherParam = va_arg(args, NSString *);
if(paramSum.length > 0){
if(otherParam.length > 0){
paramSum = [NSString stringWithFormat:@"%@/%@",paramSum,otherParam];
}
}else{
if(otherParam.length > 0){
paramSum = otherParam;
}
}
}
va_end(args);
return paramSum;
}
+ (NSString *)getGoodsRuleWithCarLength:(NSString *)carLength andCarType:(NSString *)carType andSpecialRequire:(NSString *)specialRequire andEntrance:(TYTGoodsRuleEntrance)entrance{
//用"/"拼接字符串
NSString *goodsRule = [NSString stringSplicWithSlantParamsCount:3, carLength, carType, specialRequire];
return goodsRule;
}
很明显,第二中方法扩展性更好,逼格更好
也曾考虑过在封装的代码中通过vsnprintf计算可变参数的长度,但是参数有可能为空,就会导致崩溃,所以最后决定直接传进来参数的个数
微信图片_20190703142139.jpg
##关注作者