如何使基于NSString的切换语句更加高效和可扩展?

Ber*_*rnd 1 objective-c ios

我有很多基于按钮的字符串值的切换语句(例如,将箭头图像移动到UIButton的坐标).我意识到我的代码中有很多重复.我想到的一件事是例如使用实际的"切换"功能但不幸的是它只使用int作为切换变量类型而不是字符串.

这是我正在寻求改进的代码示例:

-(void)initAperture{

//Set
if ([[[self dataObject] logAperture] isEqualToString:@"dark"]) {
    [self moveImageView:selectorAperture
              toUIButton:buttonApertureDark
               animated:NO];
} 
if ([[[self dataObject] logAperture] isEqualToString:@"cloudy"]) {
    [self moveImageView:selectorAperture
             toUIButton:buttonApertureCloudy
               animated:NO];
} 
if ([[[self dataObject] logAperture] isEqualToString:@"sunny"]) {
    [self moveImageView:selectorAperture
              toUIButton:buttonApertureSunny
               animated:NO];        
} 
if ([[[self dataObject] logAperture] isEqualToString:@"pinhole"]) {
    [self moveImageView:selectorAperture
              toUIButton:buttonAperturePinhole
               animated:NO];
} 

}
Run Code Online (Sandbox Code Playgroud)

任何改进建议或最佳实践表示赞赏.

Tim*_*ddy 5

用于NSDictionary键是这些NSString对象的位置,对象是UIButton对象.

然后将您的if逻辑替换为:

[self moveImageView:selectorAperture toUIButton:[_myDictionary objectForKey:[[self dataObject] logAperture] animated:NO]];
Run Code Online (Sandbox Code Playgroud)

我只是从我的手指上打字,所以我不确定它会编译......但我认为我的例子"足够好".