Search code examples
objective-ccs193p

CS193P - Assignment 2, descriptionOfTopOfStack:, recursive class method


below is a class method that always returns null -when, for example, stack = 2,2,"+" I want it to return "2+2"

In the initial iteration the method correctly determines the topOfStack is a NSString rather than a NSNumber but is doesn't create NSString 'description' to equal "2+2" by recursive calling

I feel I'm missing something obvious here, am I dealing with the strings correctly....

+ (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;
}

Solution

  • Method stringByAppendingString: returns an autoreleased string, does not modify the original one. If you want to modify description you must do something like

    description = [description stringByAppendingString: [self descriptionOfTopOfStack:stack]];
    

    Besides, writing

    NSString *description;
    

    you are just creating a pointer to a NSString, not a NSString. Use instead

    NSString* description = @"";