微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在if-case内创建NSString失败?

如何解决在if-case内创建NSString失败?

| 我只是试图以简单的if-manner方式决定要处理的文本。为什么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
    

解决方法

您需要这样做:
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
仍未声明。 由于编译器不知道从理论上讲是否有可能使您的所有条件均告失败,因此无论如何它只会警告您。 通常,您应该/必须始终在变量将要使用的范围内初始化变量。在您的情况下,
cellValue
超出了
cell.textLabel.text = cellValue;
的范围。 有点题外话,但对于任何UI字符串,也应使用ѭ5代替硬编码。     ,
 NSString *cellValue = NULL; 

if(indexPath.row == [listOfItems count]) {
    cellValue = [[NSString alloc] initWithFormat:@\"Totalt: %@st registrerade\",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!
    ,您的方式定义了两个都命名为
cellValue
的NSString。第一个
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;
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。