我有相同功能在不同条件下使用两次以上的代码。所以我决定使用Goto语句。但是这个代码将在for循环中执行。所以我不明白如何在同一个函数中调用相同的代码。我不想再创建一个功能。我的代码是......
- (void)setSelectedSearchCriteria:(NSString *)storedValue storedTag:(NSString *)storedTag D_Key:(NSString *)D_Key D_Tag_Value:(NSString *)D_Tag_Value arrayMain:(NSMutableArray *)arrayMain bgView:(UIView *)bgView
{
//Add data
NSMutableArray *sArray = [[storedValue componentsSeparatedByString:@","] mutableCopy];
NSMutableArray *sTagArray = [[storedTag componentsSeparatedByString:@","] mutableCopy];
[sArray removeObject:@""];
[sTagArray removeObject:@""];
int maxTag = 0;
if (sTagArray.count != 0)
{
maxTag = [[sTagArray valueForKeyPath:@"@max.intValue"] intValue];
for (int i = maxTag + 1; i <= [D_Tag_Value intValue]; i++)
goto add_value;
}
else
goto add_value;
add_value:
{
NSString *D_Value = [[arrayMain objectAtIndex:[D_Tag_Value intValue]] valueForKey:PARAMETER_KEY];
if (![sArray containsObject:D_Value])
{
[sArray addObject:D_Value];
[sTagArray addObject:D_Tag_Value];
}
//Add data
UIButton *btn = (UIButton *)[bgView viewWithTag:[D_Tag_Value intValue]];
[self setSelectedButtonStyle:btn];
}
storedValue = [[[sArray valueForKey:KEY_DESCRIPTION] componentsJoinedByString:@","] mutableCopy];
storedTag = [[[sTagArray valueForKey:KEY_DESCRIPTION] componentsJoinedByString:@","] mutableCopy];
[SEARCH_CRITERIAS setValue:storedValue forKey:D_Key];
[SEARCH_CRITERIAS_TAG setValue:storedTag forKey:D_Key];
}
在for循环中执行的add_value内部的代码以及在else部分中执行的代码。所以我不知道如何管理它。
答案 0 :(得分:1)
在函数中定义一个块
void(^theBlock)(void) = ^(){
NSString *D_Value = [[arrayMain objectAtIndex:[D_Tag_Value intValue]] valueForKey:PARAMETER_KEY];
if (![sArray containsObject:D_Value])
{
[sArray addObject:D_Value];
[sTagArray addObject:D_Tag_Value];
}
//Add data
UIButton *btn = (UIButton *)[bgView viewWithTag:[D_Tag_Value intValue]];
[self setSelectedButtonStyle:btn];
};
我不完全明白你在add_value中做了什么。如果它可以改变为块接收一些参数并返回一些更好的值
之后你只需要调用块
theBlock();
答案 1 :(得分:1)
代码实际上并不依赖于循环计数器,因此重构代码并不困难,因此您可以简单地执行循环适当的次数。
project1/protected/controllers