Reputation: 1751
I'm trying to perform the relatively simple task of deleting the items in an NSMutableArray that fit a certain criteria.
In this particular case, I'd like to delete the items where all of the following are true:
An NSLog of my array looks like this:
array = (
{
city = "Seattle";
state = "WA";
timestamp = 1432844384;
},
{
city = "Dallas";
state ="TX";
timestamp = 1432844415;
},
{
city = "Seattle";
state = "WA";
timestamp = 1432845329;
}
)
I've tried using NSPredicate to filter the array, but I think that may be overcomplicating things. Any recommendations would be great! Thank you!
Upvotes: 1
Views: 103
Reputation: 16650
No, filtering out the items to delete and then deleting them is the right way. It iw not complicated, because obviously getting the specified items is filtering with a predicate + deleting them is deleting them. How could a solution be less complicated?
Maybe it is easier to you, to filter out the items not to delete. Simply add a NOT
to your predicate.
Upvotes: 1
Reputation: 541
Here your timestamp is unique every time. So you have delete data base on timestamp.
First you have to get index of that timestamp from that array.
NSInteger index = [[array valueForKey:@"timestamp"] indexOfObject:timestamp];
After getting this index of array you have to delete data from that index.
[array removeObjectAtIndex:index];
Upvotes: 0
Reputation: 803
You could get the indexes of such elements by using indexesOfObjectsPassingTest:
(see docs)
NSIndexSet *indexes = [array indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
// check if obj is matching all your criteria
}
Then remove the items using removeObjectsAtIndexes:
(see docs)
[array removeObjectsAtIndexes:indexes];
Upvotes: 4