下面是一个总是返回null的类方法 - 例如,stack = 2,2,“+”我希望它返回“2 + 2”
在初始迭代中,该方法正确地确定topOfStack是NSString而不是NSNumber但是不会通过递归调用将NSString'description'创建为等于“2 + 2”
我觉得我在这里遗漏了一些明显的东西,我是否正确地处理了琴弦......
+ (NSString *) descriptionOfTopOfStack: (NSMutableArray * ) stack
{
NSString *description;
id topOfStack = [stack lastObject]; // get last object
if (topOfStack) [stack removeLastObject]; // then remove it from stack
if ([topOfStack isKindOfClass:[NSNumber class]]) { // is last object a number?
return [topOfStack stringValue]; // if so then return it, **done***
}
else if ([topOfStack isKindOfClass:[NSString class]])
{
if ([topOfStack isEqualToString:@"+"])
{
[description stringByAppendingString: [self descriptionOfTopOfStack:stack]];
[description stringByAppendingString:@"+"];
[description stringByAppendingString: [self descriptionOfTopOfStack:stack]];
}
}
NSLog(@"Description is %@", description);
return description;
}
答案 0 :(得分:1)
方法stringByAppendingString:返回自动释放的字符串,不会修改原始字符串。如果您想修改description
,您必须执行类似
description = [description stringByAppendingString: [self descriptionOfTopOfStack:stack]];
此外,写作
NSString *description;
您只是创建指向NSString
的指针,而不是NSString
。改为使用
NSString* description = @"";