I have been working with NSArrays and NSMutableArrays that store NSDate objects for a few days now. I noticed that calling [listOfDates removeObject:date1] removes all the NSDate objects from the array. I have instead been doing this to remove objects:
NSMutableArray *dateList; // Has Dates in it
NSDate *dateToRemove; // Date Object to Remove
__block NSUInteger indexToRemove;
__block BOOL foundMatch = NO;
[dateList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([obj isEqualToDate:dateToRemove]) {
indexToRemove = idx;
foundMatch = YES;
*stop = YES;
}
}];
if (foundMatch) {
[dateList removeObjectAtIndex:indexToRemove];
}
Is there a better way to be doing this? Perhaps another data structure? Or a simpler function?
You should use the first method you tried:
This will remove date1 and ONLY date1 from
listOfDates. This should NOT remove all NSDate objects fromlistOfDatesunless all NSDate objects inlistOfDatesaredate1.You could also use removeObjectAtIndex: combined with indexOfObject: to product the same effect, but that’s extra code.
From the NSMutableArray class reference for
removeObject: