3
votes

I've got an Mutable NSArray storing object types (ids - NSNumber, NSString) that will store digits (1,2,3,4, etc), operations (+,-,/,*, etc.), and variables (x,y,z, etc.). I have the variables and related values stored in an NSDictionary, keys are NSStrings equal to x,y,z with NSNumber values 5,5,2 respectively. I want to replace my variable in my NSArray with the actual value stored in my NSDictionary. I keep getting the following error when I attempt to replace the object. Please help.

-[__NSArrayI replaceObjectAtIndex:withObject:]: unrecognized selector sent to instance

        NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:
                              [NSNumber numberWithDouble:5],@"x",  
                              [NSNumber numberWithDouble:5],@"y", 
                              [NSNumber numberWithDouble:2],@"z", 
                              nil];

+ (double)runProgram:(id)program
 usingVariableValues:(NSDictionary *)variableValues;
{
    // introspection - ensure program is NSArray and variableValues is NSDictionary
    if ([program isKindOfClass:[NSArray class]] && [variableValues isKindOfClass:    [NSDictionary class]])
    {
        // array for program stack
        NSMutableArray *stack = [program copy];

        // Loop to replace variables with actual values in NSDictionary
        for (NSUInteger i = 0; i < [stack count]; i++)
        {
            NSLog(@"object at index = %@", [stack objectAtIndex:i]);
        if ([[stack objectAtIndex:i] isKindOfClass:[NSString class]] && [[stack     objectAtIndex:i] isEqualToString: @"x"])
            {
                 // replace variable with value in corresponding value in dictionary
                NSNumber *numberKeyValue = [variableValues objectForKey:@"x"];
                [stack replaceObjectAtIndex:i withObject:numberKeyValue];
            }
        }
return 0
}
1

1 Answers

10
votes

NSArray's copy method always returns an immutable array, regardless of whether the original was mutable or immutable. If you want a mutable copy, you need to use mutableCopy. (It's a Cocoa convention. NSString, NSDictionary, and generally any class that has mutable and immutable variants will work the same way.)