1

I have a NSMutableArray is my delegate that I am using in one of my view controllers as well.

So in viewDidLoad I make a mutable copy of my NSMutableArray like this

@implementation ItemsViewController{
    AppDelegate *mydelegate;
    NSMutableArray* allItems;
}

In viewDidLoad

allItems = [mydelegate.array mutableCopy];

Now whatever changes I make in my allItems MutableArray also cause changes in my mydelegate.array. Am I doing something wrong?

Also my array in the delegate is defined as follows

@property (nonatomic, strong) NSMutableArray *array;
Jonathan
  • 2,728
  • 10
  • 43
  • 73
  • What kinds of change you made to allItems? – KudoCC Nov 05 '13 at 09:36
  • @KudoCC allitems contains Directories. So I am updating the directories. essentially replacing the old directories with the updated ones with replaceObjectAtIndex – Jonathan Nov 05 '13 at 09:38
  • If you just make change to allItems's construct, I think it won't affect mydelegate.array . If it does, I advice you `NSLog(@"%@, %@", allItems, mydelegate.array)` to check the address of them. – KudoCC Nov 05 '13 at 09:52

4 Answers4

2

I assume you did not implemented the mutableCopyWithZone: correctly.

You need to implement the NSMutableCopying protocol for the objects you put in the array, this way you could pass a new instance of that object for that case.

- (id)mutableCopyWithZone:(NSZone *)zone
{
   YourCustomModel *aCopy = [[[self class] allocWithZone:zone] init];
   if (aCopy) {
     // set properties
}
   return aCopy
}
NSMutableString
  • 10,493
  • 1
  • 21
  • 27
2

You should do a deepCopy, i use this one and works perfectly, made by Sherm Pendley †.

Community
  • 1
  • 1
Laszlo
  • 2,803
  • 2
  • 28
  • 33
0

That's because the mutable copy of the array is referencing the same objects as mydelegate.array is referencing, so if you change one object property, it's changed in both arrays, as it's the same object.

You could implement NSCopying protocol in your objects and you can then call initWithArray:copyItems: NSArray method.

Hope that helps.

Adrián Rodríguez
  • 1,836
  • 15
  • 16
0

Try this.

allitems =[NSMutableArray arrayWithArray:mydelegate.array];
Shob-Z
  • 891
  • 6
  • 26