Reputation: 615
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:
[objectsArray addObject:myObject]
, the object is added properly.replaceObjectAtIndex:0 withObject:myObject
.Any thoughts would be very much appreciated.
Upvotes: 3
Views: 65
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 Object
s.
Upvotes: 1