Hersh Bhargava
Hersh Bhargava

Reputation: 615

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:

Any thoughts would be very much appreciated.

Upvotes: 3

Views: 65

Answers (1)

Aaron Brager
Aaron Brager

Reputation: 66292

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.

Upvotes: 1

Related Questions