0

I'm relatively new to objective-C and I'm having a problem with a 2D NSMutableArray and it's behaviour when adding the contents of one NSMutableArray to another.

I have a singleton class containing an NSMutableArray. This array is for storing NSURL values. At a certain point in my program, I need to add this NSMutableArray as a whole to another NSMutableArray.

I do something like this: [arrayIWantStuffIn addObject: mySingleton.singletonMutableArray];

The problem I have is that I need to reset my singltonMutableArray to start storing a new set of NSURL values. The addObject function above appears to be passing by reference rather than passing by value, so when I do:

[mySingleton.singletonMutableArray removeAllObjects];

The data stored in arrayIWantStuffIn is wiped as well.

How can I achieve a 'deep' addObject that is adding a NSMutableArray to another NSMutableArray by value and not by reference?

1 Answer 1

0

You dont actually need a deep copy just another mutableCopy. This can be done simply by doing the following

[arrayIWantStuffIn addObject: [[mySingleton.singletonMutableArray mutablCopy] autorelease]];

Once that is done when the singletonMutableArray is cleared or changed it will not change your items in arrayIWantStuffIn and you can still modify the contents independently.

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

2 Comments

That worked like a charm. Thanks Joe. Just the make sure I'm understanding this correctly, the [mySingleton.singletonMutableArray mutableCopy] makes a deep copy of my singletonMutableArray and then uses that copy as the object passed to addObject?
It will not make a deep copy of your singletonMutableArray so the mutableCopy will still point to the same NSURL's at the time of the copy but when you make changes to singletonMutableArray it will not change your arrayIWantStuffIn and vice versa. Also NSURL's are immutable so you do not have to worry about those changing.

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.