2

大约一周前我开始了 Objective-C 编程,并且一直坚持从传递给函数的字符串数组创建一个新字符串。我已经对此进行了彻底的研究,似乎无法弄清楚为什么我可以使用stringByAppendingString一次(检查NSLog)但不能第二次使用而不抛出此错误:

感谢您的关注。

2012-06-29 20:46:35.761 计算器[32883:f803]-[__NSCFNumber stringByAppendingString:]:无法识别的选择器发送到实例 0x6e43d50

2012-06-29 20:46:35.763 计算器 [32883:f803] *由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[__NSCFNumber stringByAppendingString:]:无法识别的选择器发送到实例 0x6e43d50”

+ (NSString *)descriptionOfTopOfStack:(NSMutableArray *)stack
{
    NSString *result;
    NSString *displayString = [[NSString alloc]init];
    id topOfStack = [stack lastObject];
    if (topOfStack) [stack removeLastObject];

    if ([self isNoOperandOperation:topOfStack]) {
        displayString = [displayString stringByAppendingString:topOfStack];
        result = displayString;
        }
    else if ([self isOperation:topOfStack]){
        id nextInStack = [stack lastObject];
        if (topOfStack) [stack removeLastObject];
        displayString = [displayString stringByAppendingString:nextInStack];
        displayString = [displayString stringByAppendingString:topOfStack];
        result = displayString;
4

2 回答 2

1

stringByAppendingString 是 NSString 的一个方法,你必须将你的 displayString 作为 NSString 返回,

+ (NSString *)descriptionOfTopOfStack:(NSMutableArray *)stack
{
NSLog(@"stack array :: %@",stack);
NSString *result;
NSString *displayString = [[NSString alloc]init];
id topOfStack = [stack lastObject];
if (topOfStack) [stack removeLastObject];

NSLog(@"topOfStack :: %@", (NSString*)topOfStack);

if ([self isNoOperandOperation:topOfStack]) {
    displayString = [[(NSNumber*)displayString stringValue] 
                                stringByAppendingString:(NSString*)topStack];
    result = displayString;
    }
else if ([self isOperation:topOfStack]){
    id nextInStack = [stack lastObject];
    if (topOfStack) [stack removeLastObject];
    displayString = [[(NSNumber*)displayString stringValue] 
                                stringByAppendingString:(NSString*)nextInStack];
    displayString = [[(NSNumber*) displayString stringValue] 
                                stringByAppendingString:(NSString*)topStack];
    result = displayString;

编辑:stringByAppendingString 方法需要 NSString 的参数类型,您的 topOfStack 是类型 ID,假设您的 topOfStack 是字符串,您需要将其类型转换为 NSString,与 nextInStack 相同

于 2012-06-30T04:05:38.097 回答
0

您需要id先将您的转换为字符串。对于 NSNumbers,您可以使用-stringValue.

于 2012-06-30T04:05:50.730 回答