【问题标题】:unused expression未使用的表达式
【发布时间】:2012-07-30 17:22:02
【问题描述】:

这里是新手。在以下代码中:

+ (NSString *)descriptionOfProgram:(id)program
{
    NSMutableArray *mutableCopyOfProgram = [program mutableCopy];
    NSString *descr = @"";
    for (int i=0; i<mutableCopyOfProgram.count; i++)
    {
        descr = [descr stringByAppendingString:(@"%@",[mutableCopyOfProgram objectAtIndex:i])];
    }
    return descr;
}

循环中的代码不断收到“表达式结果未使用”警告。但这怎么可能呢,在下一行我返回表达式结果时呢?

【问题讨论】:

    标签: objective-c ios5 xcode4.3


    【解决方案1】:

    您收到的警告是因为您应该使用stringByAppendingFormat: 方法而不是stringByAppendingString:。无论如何,我建议使用NSMutableString 来构建字符串。此外,最好使用[mutableCopyOfProgram count] 而不是mutableCopyOfProgram.count。以下代码应该适合您:

    + (NSString *)descriptionOfProgram:(id)program
    {
        NSMutableArray *mutableCopyOfProgram = [program mutableCopy];
        NSMutableString *descr = [[NSMutableString alloc] init];
        for (int i=0; i < [mutableCopyOfProgram count]; i++)
        {
            [descr appendFormat:@"%@", [mutableCopyOfProgram objectAtIndex:i]];
        }
        return descr;
    }
    

    【讨论】:

    • 非常感谢 - 我很感激。一个新手问题:在这种情况下,NSMutableString 和 [mutableCopyOfProgram count] 如何/为什么比 NSString 和 mutableCopyOfProgram.count 更合适?
    • NSMutableString 将比多次创建NSString 更有效。点符号只能用于属性。
    【解决方案2】:

    使用stringByAppendingFormat: 代替stringByAppendingString:

    我认为在您使用 stringByAppendingString: 时不会使用 [mutableCopyOfProgram objectAtIndex:i],所以那将是未使用的。

    格式类似于@"%@", @"a string",而字符串只是@"a string",因此如果要使用格式,请确保使用正确的方法。

    【讨论】:

      【解决方案3】:

      你有一些杂散的括号 (),也应该使用stringByAppendingFormat:

      + (NSString *)descriptionOfProgram:(id)program
      {
          NSMutableArray *mutableCopyOfProgram = [program mutableCopy];
          NSString *descr = @"";
          for (int i=0; i<mutableCopyOfProgram.count; i++)
          {
              descr = [descr stringByAppendingFormat:@"%@", [mutableCopyOfProgram objectAtIndex:i]];
          }
          return descr;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-25
        • 1970-01-01
        • 2021-01-03
        • 2020-12-18
        • 2020-10-17
        • 1970-01-01
        相关资源
        最近更新 更多