netmajor
netmajor

Reputation: 6585

Copy NSMutableArray and change it

I have method :

-(void)ModifyArray:(NSMutableArray)orginalArray
{
 NSMutableArray* copy = [[NSMutableArray alloc]init];
 copy = [orginalArray copy];
 Field* field = [copy objectAtIndex:0];
 [copy replaceObjectAtIndex:0 withObject:field];
}

I get error in last line that prevent me from changing copy array.

When I use mutableCopy instead copy, I can change copy array but my orginalArray also change :/ I only want to create copy od orginalArray without references to it and chnage only thin new array.

Upvotes: 0

Views: 100

Answers (1)

Michael Dautermann
Michael Dautermann

Reputation: 89509

I see a few problems in here.

number 1 )

get rid of that first line, which is:

NSMutableArray* copy = [[NSMutableArray alloc]init];

It's made useless by that second "[originalArray copy]; line.

Use this instead:

NSMutableArray * copy = [originalArray mutableCopy];

or better yet:

NSMutableArray * myOriginalArrayCopy = [originalArray mutableCopy]; 

(see my last point in this answer)

number 2)

Your declaration needs a pointer:

-(void)modifyArray:(NSMutableArray *)orginalArray

(notice I also changed the first letter of "ModifyArray" to lower case? Best practice in Objective-C is that method names should start with lower case letters)

number 3)

Don't use "copy" as a name for a variable. It looks bad (and it's probably a language keyword, too).

Are you even doing anything with that "copy" mutable array at the end of your "modifyArray" function?

Upvotes: 3

Related Questions