objective-c - 怎样才能让下面的代码变干呢?

标签 objective-c cocoa dry

如何使我的以下代码“DRY”(不要重复自己)

- (void)updateLetterScore { // NOT DRY... Must fix
    if (percentScore < 60.0)
        letterLabel.text = [NSString stringWithFormat:@"F"];

    if (percentScore > 59.0 && percentScore < 64.0)
        letterLabel.text = [NSString stringWithFormat:@"D-"];

    if (percentScore > 64.0 &&  percentScore < 67.0)
        letterLabel.text = [NSString stringWithFormat:@"D"]; 

    if (percentScore > 66.0 &&  percentScore < 70.0)
        letterLabel.text = [NSString stringWithFormat:@"D+"]; 

    if (percentScore > 69.0 &&  percentScore < 74.0)
        letterLabel.text = [NSString stringWithFormat:@"C-"]; 

    if (percentScore > 73.0 &&  percentScore < 76.0)
        letterLabel.text = [NSString stringWithFormat:@"C"];

    if (percentScore > 76.0 &&  percentScore < 80.0)
        letterLabel.text = [NSString stringWithFormat:@"C+"];

    if (percentScore > 79.0 &&  percentScore < 84.0)
        letterLabel.text = [NSString stringWithFormat:@"B-"];

    if (percentScore > 83.0 &&  percentScore < 86.0)
        letterLabel.text = [NSString stringWithFormat:@"B"];

    if (percentScore > 85.0 &&  percentScore < 90.0)
        letterLabel.text = [NSString stringWithFormat:@"B+"];

    if (percentScore > 89.0 &&  percentScore < 94.0)
        letterLabel.text = [NSString stringWithFormat:@"A-"];

    if (percentScore > 93.0 &&  percentScore < 100.0)
        letterLabel.text = [NSString stringWithFormat:@"A"];

    if (percentScore == 100)
        letterLabel.text = [NSString stringWithFormat:@"A+"];
}

谢谢你的提示。我只是想知道你们的想法,因为这个小片段在我的代码中看起来很可怕。

最佳答案

一种方法(伪代码,因为我不知道 Objective-C ):

grades = ["F", "D-", "D", ...]
scores = [60.0, 64.0, 67.0, ...]

for(i = 0; i < grades.count; i = i + 1)
{
   if(score < scores[i])
   {
     letterLabel.text = [NSString stringWithFormat:@"%@", grades[i]]
     break;
   }
}

关于objective-c - 怎样才能让下面的代码变干呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/989870/

相关文章:

ios - 在 iOS 7 中查看 Core Data 创建的 sqlite 文件时出现问题

python - Django:优化违反 DRY 的测试

c# - 干这个方法

iphone - ios4中如何执行网络后台

ruby-on-rails - 如何通过提取另一个模型的名称来确定模型?

IOS UIDynamicAnimator masksToBounds 不会将碰撞作为边界

objective-c - NSUserNotification 基于每个通知更改通知图像/ Logo

php - 在 iOS 中检索 SQL 数据

cocoa - 有效地子类化标准 Cocoa 控件

objective-c - 编码CGSize :forKey: and decodeCGSizeForKey: equivalent for OS X