0

I have and NSMutableArray and I want to replace it with another, but if I try to do it like this...

firstArray = secondArray;

...then it seems to erase the entire firstArray and I get this error message..

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSCFArray objectAtIndex:]: index (0) beyond bounds (0)'

...and the bounds should be (6) not (0).

Is there a correct way to replace the array?

PS: I already checked the secondArray and it functions fine.

2 Answers 2

1

If you want to make the firstArray variable into a reference to the second, do this:

[firstArray release];
firstArray = [secondArray retain];

If you want to make firstArray a copy of the second, do:

[firstArray release];
firstArray = [secondArray mutableCopy];

(In both cases, the release presupposes you allocated the array or have previously retain-ed or copy-ed it. If not, you can skip that bit. Either way you do own the new array and must release it at an appropriate time.)

If you want to replace the contents of the first array with those of the second (which isn't much different in consequence from taking a copy, but involves one less object destruction and creation), then I think you'll have to do something like this:

[firstArray removeAllObjects];
[firstArray addObjectsFromArray:secondArray];
Sign up to request clarification or add additional context in comments.

1 Comment

[secondArray copy] will return an immutable copy.
0

You're assigning the firstArray pointer to that of the secondArray pointer, so you lose the reference to the firstArray object, and it gets leaked. If you want to replace the objects in the firstArray object, use something like -replaceObjectsInRange:withObjectsFromArray: or just -release the firstArray object and assign firstArray to [secondArray mutableCopy].

I recommend reading up on C pointers as well as Objective-C memory management rules to make sure you've got a firm grasp on the fundamentals.

2 Comments

I still get the same error. I even tried... for (int place=0;place<7;place++) { [firstArray replaceObjectAtIndex:place withObject:[secondArray objectAtIndex:place]]; } ...and it still sets the range of firstArray to (0). Anything else.
Nevermind, I fixed that problem but now I have a new one. I post on a new question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.