using copy in nested NSMutableArrays gives immutable objects?

  • In my program I have nested NSMutableArrays, i.e., each element in a
    root NSMutableArray is a NSMutableArray.

    When I try to grab one of the element NSMutableArrays ......
    NSMutableArray *copyOfCurrent = (NSMutableArray *) [[walkerArray
    objectAtIndex:lastNodeInCurrent] copy];//walkerArray is another
    NSMutableArray

    As soon as I try to alter (insert an element for example)
    copyOfCurrent I get a "NSInternalInconsistencyException" with the
    message "mutating method sent to immutable object".  It looks like
    either the objectAtIndex or the copy method is providing something
    immutable, not an NSMutableArray.

    Any idea why that might be happening?

    I was able to get around the problem by creating a new NSMutableArray
    and loading into it the contents of the immutable one like ..

    NSMutableArray *copyOfCurrent = (NSMutableArray *) [[walkerArray
    objectAtIndex:lastNodeInCurrent] copy];
    NSMutableArray *fixError = [[NSMutableArray alloc] init];
    int k;
    for (k = 0; k < [copyOfCurrent count]; k++)
    {
    fixError[k] = copyOfCurrent[k];
    }

    But that seems hokey and I would like to understand the cause of the
    original issue.

    Thanks;

    Randy
  • On Nov 15, 2008, at 10:56 PM, Randy wrote:

    > In my program I have nested NSMutableArrays, i.e., each element in a
    > root NSMutableArray is a NSMutableArray.
    >
    > When I try to grab one of the element NSMutableArrays ......
    > NSMutableArray *copyOfCurrent = (NSMutableArray *) [[walkerArray
    > objectAtIndex:lastNodeInCurrent] copy];//walkerArray is another
    > NSMutableArray
    >
    > As soon as I try to alter (insert an element for example)
    > copyOfCurrent I get a "NSInternalInconsistencyException" with the
    > message "mutating method sent to immutable object".  It looks like
    > either the objectAtIndex or the copy method is providing something
    > immutable, not an NSMutableArray.
    >
    > Any idea why that might be happening?
    >
    > I was able to get around the problem by creating a new
    > NSMutableArray and loading into it the contents of the immutable one
    > like ..
    >
    > NSMutableArray *copyOfCurrent = (NSMutableArray *) [[walkerArray
    > objectAtIndex:lastNodeInCurrent] copy];
    > NSMutableArray *fixError = [[NSMutableArray alloc] init];
    > int k;
    > for (k = 0; k < [copyOfCurrent count]; k++)
    > {
    > fixError[k] = copyOfCurrent[k];
    > }
    >
    > But that seems hokey and I would like to understand the cause of the
    > original issue.
    >
    > Thanks;
    >
    > Randy

    -copy returns an immutable object (as you found out), -mutableCopy is
    what you want.

    --Nathan
previous month november 2008 next month
MTWTFSS
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
Go to today
MindNode
MindNode offered a free license !