if-case内部创建NSString失败?

时间:2011-04-15 10:51:44

标签: objective-c

我只是想以一种简单的if方式决定我要使用哪个文本。为什么X代码会抱怨而不是让我构建项目,说明变量在if中明确定义时是未定义的?

 if(indexPath.row == [listOfItems count]) {
            NSString *cellValue = [[NSString alloc] initWithFormat:@"Totalt: %@st registrerade", companyTotalReg]; //cellValue is unused
        } else {
            NSString *cellValue = [[NSString alloc] initWithFormat:@"Totalt: SEK%@ intjänat", companyTotalPay]; //cellValue is unused
        }
        cell.textLabel.text = cellValue; //cellValue is undefined

3 个答案:

答案 0 :(得分:3)

你需要这样做:

NSString *cellValue = nil;
if(indexPath.row == [listOfItems count]) {
    cellValue = [[NSString alloc] initWithFormat:@"Totalt: %@st registrerade", companyTotalReg]; //cellValue is unused
} else {
    cellValue = [[NSString alloc] initWithFormat:@"Totalt: SEK%@ intjänat", companyTotalPay]; //cellValue is unused
}
cell.textLabel.text = cellValue; //cellValue is not undefined anymore

否则,从理论上讲,你的if子句都会失败(即使在你的情况下这是不可能的)并且cellValue仍未声明。 由于编译器无法知道理论上是否可能使所有条件都失败,所以无论如何它都会警告你。

一般情况下,你应该/必须始终初始化将要使用它们的变量within the scope 。对于cellValue

cell.textLabel.text = cellValue; 将超出范围

有点偏离主题,但you should also use NSLocalizedString()代表任何UI字符串,而不是硬编码字符串。

答案 1 :(得分:1)

 NSString *cellValue = NULL; 

if(indexPath.row == [listOfItems count]) {
    cellValue = [[NSString alloc] initWithFormat:@"Totalt: %@st registrerade", companyTotalReg]; //cellValue is unused
} else {
    cellValue = [[NSString alloc] initWithFormat:@"Totalt: SEK%@ intjänat", companyTotalPay]; //cellValue is unused
}
cell.textLabel.text = [cellValue autorelease]; // The autorelease is here because you are leaking the memory otherwise. If you release the string later anyway, you can and should remove it!

答案 2 :(得分:0)

你这样做的方式定义了两个名为cellValue的NSStrings。第一个cellValue的生命周期仅限于if子句的范围,第二个cellValue的生命周期仅限于else子句的范围。您可以通过两种方式解决此问题:

NSString *cellValue;
if (indexPath.row == [listOfItems count])
    cellValue = [[NSString alloc] initWithFormat:@"Totalt: %@st registrerade", companyTotalReg];
else
    cellValue = [[NSString alloc] initWithFormat:@"Totalt: SEK%@ intjänat", companyTotalPay]; 
cell.textLabel.text = cellValue;

NSString *cellValue = (indexPath.row == [listOfItems count])
    ? [[NSString alloc] initWithFormat:@"Totalt: %@st registrerade", companyTotalReg]
    : [[NSString alloc] initWithFormat:@"Totalt: SEK%@ intjänat", companyTotalPay];
cell.textLabel.text = cellValue;