abh
abh

Reputation: 1249

Edit contents of NSMutableArray who's name is stored in contents of NSString

I have a function that accepts NSString variable in parameters and appends Array at the end which gives it the name of array already defined in class. How can i edit that array ?

-(void) editArray:(NSString*)str{ //suppose str value is first 

NSString* myArrayName = [str stringByAppendingString:@"Array"]; //firstArray  

myArrayName contains the name of NSMutableArray already defined in class.. How can i access this array and edit it's values ?

NSMutableArray *myArray=[self valueForKey:myArrayName]; //suppose myArrayName is equal to @"firstArray"

The above technique is not working as it copies the contents of firstArray to myArray and if i change contents of myArray it doesn't effect firstArray

Upvotes: 0

Views: 51

Answers (2)

Zeeshan
Zeeshan

Reputation: 4244

Make one nsarray *array alloc it and add your values in it. Then add the values by method addValuesFromArray from array in your reference array.

Don't allocate your reference array as it will lose previous reference.

Upvotes: 2

Mykola Denysyuk
Mykola Denysyuk

Reputation: 1985

Actually, you are wrong. If your class instance has property(or iVar) of NSMutableArray (as you called it 'firstArray'), and it's instantiated, when you calls

NSMutableArray *myArray=[self valueForKey:myArrayName];

myArray and your defined variable firstArray will reference to the same NSMutableArray object. So if after that you change contents of myArray (for example [myArray removeLastObject]), myArray and firstArray will still reference to same array object (which will now contain objectsCount-1.)

Hence, mistake can be if you assign to myArray another object and expect that firstArray will also reference to this object:

NSMutableArray *myArray=[self valueForKey:myArrayName]; //firstArray and myArray becomes equal
myArray = [NSMutableArray arrayWithArray:anotherArray]; //firstArray and myArray not equal anymore!

Upvotes: 1

Related Questions