Search code examples
objective-carraysnsarray

Replacing Object in Array doesn't work, but Adding a new one Does


I have a function that is designed to take an object, and, if one with the same identifier string already exists in an array, update it, and if it doesn't, add the object. The adding part works, but for some reason the update functionality loses data.

Here is my code:

- (void)addOrUpdateGroup:(Object *)myObject
{
    for (H2Group *existingObject in objectsArray) {
        if ([existingObject.identifier isEqualToString:myObject.identifier]) {
            [objectsArray replaceObjectAtIndex:[objectsArray indexOfObject:existingObject] withObject:myObject];
            return;
        }
    }
    [objectsArray addObject:myObject];    
}

When calling this method with an object that has a counterpart in the array, it executes, but does not seem to replace the object.

Using breakpoints and logs, I have ascertained that:

  • The loop is entered, and the detection of a new object with an existing identifier works fine.
  • The new object is intact and if I instead use [objectsArray addObject:myObject], the object is added properly.
  • The same problem occurs if I use replaceObjectAtIndex:0 withObject:myObject.

Any thoughts would be very much appreciated.


Solution

  • Something like this is more efficient, safer, and (in my opinion) more readable:

    - (void)addOrUpdateGroup:(Object *)myObject {
        NSUInteger idx = [objectsArray indexOfObjectPassingTest:^(Object *object, NSUInteger idx, BOOL *stop) {
            return [object.identifier isEqualToString:myObject.identifier];
        }];
    
        if (idx != NSNotFound) {
            [objectsArray replaceObjectAtIndex:idx withObject:myObject];
        } else {
            [objectsArray addObject:myObject];    
        }
    }
    

    It presupposes that objectsArray contains only Objects.