0

I have 2 arrays: _user.itemList(global) and updatedList(specific to that class).

for(Item *item in _user.itemList) {
    if(![item.isLinked isEqualToString: @"YES"]  && item != self.item) {
        [updatedList addObject:item];
    }
}

Item *item = updatedList[0];
item.isLinked = @"YES";

Now, I don't want the value changed in _updatedList to be reflected in _user.itemList till I press save.

But since we're dealing with pointers here, _user.itemList[0]'s isLinked is being set to "YES" immediately after this step. How do I prevent this from happening?

I've already tried mutableCopy- Instead of adding items to updatedList I do so to a new array (copArray) and set updatedList to the values of that array.

updatedItem = [copArray mutableCopy];

This doesn't work.

Aahir Giri
  • 11
  • 4

2 Answers2

0

Since you are dealing with custom object, you need to manually copy the object before you use.

Write a method in your Item class to make a copy of an instance

- (Item *)copy
{
    Item *duplicateInstance = [[Item alloc] init];
    duplicateInstance.XXXX = self.XXXX;
    // Copy all your member values to the new instance
    return duplicateInstance;
}

And replace the line

Item *item = updatedList[0];

with

Item *item = [(Item*)updatedList[0] copy];

Now your changes will not be affected with the updatedList[0] object.

If you need, you can write one more method to save the instance. For your case it will be your save action.

- (Item *)saveDataFromInstance:(Item *)backupInstance
{
    self.XXXX = backupInstance.XXXX 
    // Copy all your member values to the original instance
    return self;
}

Finally save the copied values into the original object

[(Item*)updatedList[0] saveDataFromInstance:item];
ganka
  • 191
  • 1
  • 11
0

You should put these:

Item *item = updatedList[0];
item.isLinked = @"YES";

statements inside your for loop like this:

for(Item *item in _user.itemList) {
    if(![item.isLinked isEqualToString: @"YES"]  && item != self.item) {
        item.isLinked = @"YES";
        [updatedList addObject:item];
    }
}

I think this is your purpose to set your item's isLinked = @"YES" when you have added it in the updated list. You don't need to do it after your loop.

nayem
  • 7,285
  • 1
  • 33
  • 51