如何从几个字符串? Xcode中

时间:2012-02-21 18:17:35

标签: objective-c xcode string recursion stack

我制作了一些方法,它从堆栈中获取数字和操作数,并以更加用户友好的方式显示它。问题在于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为例,这是日志:

  • 2012-02-21 22:09:39.983计算器[12536:f803] stack =( 2, 6, “+” )
  • 2012-02-21 22:09:39.983计算器[12536:f803]描述为(null)

为什么descriptionString为空?我犯了什么错误?感谢

2 个答案:

答案 0 :(得分:1)

在行中:

descriptionString = [descriptionString stringByAppendingFormat:@"%@ %@ %@",thirdInStack,topOfStack,secondInStack];

变量descriptionStringnil。用以下内容替换该行。

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);

    }

}