我制作了一些方法,它从堆栈中获取数字和操作数,并以更加用户友好的方式显示它。问题在于descriptionString变量,当topOfStack为“+”时,它会返回null。我在下面显示一个日志。
+(NSString *)descriptionOfTopOfStack:(NSMutableArray *)stack
{
NSString *descriptionString;
id topOfStack = [stack lastObject];
NSString *secondInStack;
NSString *thirdInStack;
if (topOfStack)
[stack removeLastObject];
if ([topOfStack isKindOfClass:[NSNumber class]]) {
descriptionString = [topOfStack stringValue];
}
else if([topOfStack isKindOfClass:[NSString class]]){
if(([topOfStack isEqualToString:@"+"]) || ([topOfStack isEqualToString:@"—"])){
secondInStack = [self descriptionOfTopOfStack:stack];
thirdInStack = [self descriptionOfTopOfStack:stack];
descriptionString = [descriptionString stringByAppendingFormat:@"%@ %@ %@",thirdInStack,topOfStack,secondInStack];
NSLog(@"description is %@",descriptionString);
}
}
return descriptionString;
}
我以2 + 6为例,这是日志:
为什么descriptionString为空?我犯了什么错误?感谢
答案 0 :(得分:1)
在行中:
descriptionString = [descriptionString stringByAppendingFormat:@"%@ %@ %@",thirdInStack,topOfStack,secondInStack];
变量descriptionString
为nil
。用以下内容替换该行。
descriptionString = [NSString stringWithFormat:@"%@ %@ %@",thirdInStack,topOfStack,secondInStack];
答案 1 :(得分:0)
我怀疑您没有为descriptionString
的其他分支中的if
变量设置值,因此您要将字符串附加到null
。您可以设置变量,也可以使用[NSString stringWithFormat:format]
:
if ([topOfStack isKindOfClass:[NSNumber class]]) {
descriptionString = [topOfStack stringValue];
}
else if([topOfStack isKindOfClass:[NSString class]]){
if(([topOfStack isEqualToString:@"+"]) || ([topOfStack isEqualToString:@"—"])){
secondInStack = [self descriptionOfTopOfStack:stack];
thirdInStack = [self descriptionOfTopOfStack:stack];
descriptionString = [NSString stringWithFormat:@"%@ %@ %@",thirdInStack,topOfStack,secondInStack];
NSLog(@"description is %@",descriptionString);
}
}