0

I'm having a hard time getting the hang of this. Say I have:

NSMutableArray *array1 which is already defined and has content. Now I want to create another variable, NSMutableArray *array2.

When I do [array2 addObject:someObject], I want this object to be added to array1, not to array2. How can I assign array2 so that if I make any changes to it, it modifies array1 instead?

2 Answers 2

2

You would do something this:

NSMutableArray *array1 = [NSMutable arrayWithObjects:...];
NSMutableArray *array2 = array1;

[array2 addObject:someObject];
NSLog(@"%@", array1); // should now contain 'someObject'

I am confused, however, why are you trying to create two pointers to the same object?

Sign up to request clarification or add additional context in comments.

5 Comments

Hmm..but why is this not the case for NSStrings? If I do NSString *string2=string1, then change string2, it doesn't change string1, but here if I do it with arrays, it does in fact change the original?
That is because when you set an NSString, you are changing what the pointer points to. You can call methods all you want on a pointer to an object and it will effect any other pointers to that object, but changing what that object points to requires another level of indirection.
For more information on misdirection, check out the answer I have here: stackoverflow.com/questions/9154817/…
@mohabitar no problem, just remember to accept the answer by pressing the checkmark next to the answer :)
further to the above comments, references to an NSString object are immutable, whereas NSMutableArray (as the name suggests) is mutable. this means, whenever you call a method on an NSString that "changes it" in some way, it's not really changing the original object, but creating a copy and changing that copy. NSMutableArray however, is by it's nature mutable (can change), therefore 2 ivars that point to the same mutable array point to the same changeable object. I hope this clears this up.
1

If I get your meaning correctly, you are looking for the array2 to become an alias for array1. All you need to do is assign array1 to array2:

NSMutableArray *array2 = array1;

Now calling [array2 addObject:someObject] would add elements to array1.

However, array2 is not a copy of array1: it is only another name for array1. If you create a copy, it would be completely independent of the original. In particular, adding elements to a copy would not change the content of the original in any way.

Comments

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.